建模实体关系

问题描述 投票:0回答:2

我和其他实体有EntityAEntityB的一对多关系,我们称之为DependentEntity;在EntityAOrBIdDependentEntity存储了EntityAEntityB的钥匙。

这是一个很好的设计还是我应该将外键关系分开并使用qazxsw poi和qazxsw poi列而不是通用的EntityAId列?

EntityBId
c# entity-framework
2个回答
1
投票

通过单独研究您的设计,我可以这样说:

  1. 我无法判断Dependent Entity类中的EntityAOrBId属性是否实际是Entity Id或Entity Id
  2. 类EntityB看起来像一个独立的类,可能与任何类有任何关系,也可能没有
  3. 类EntityA和类DependentEntity可以在它们之间具有循环引用

如果这就是你在这篇文章中真正的意思,那对我来说没问题。但是,如果它不完全是你的意思,那可能会产生误导。

我相信定义类的最佳实践是你需要让它们成为自我解释的类。

所以,如果是我,我会选择像这样的普通类来抽象一对多的关系:

EntityAOrBId

同样在下面的EF教程中提到:

public class EntityA { public int EntityAId { get; set; } public DependentEntity DependentEntity { get; set;} } public class EntityB { public int EntityBId { get; set; } } public class DependentEntity { public int DependentEntityId { get; set; } public int EntityAOrBId { get; set; } public string EntityType { get; set; } }

只是为了分享我的想法。

编辑:

根据您的查询和上面的EF教程,让我们看看我们是否有更多选择:

情况#1:如果一个DependentEntityId可以在实体A和B之间共享,那么该类将如下所示:

public class EntityA
{
    public int EntityAId { get; set; }
    public virtual ICollection<DependentEntity> DependentEntity { get; set; }
}

public class EntityB
{
    public int EntityBId { get; set; }
    public virtual ICollection<DependentEntity> DependentEntity { get; set; }
}

情况#2:但是如果只有A或B,那么这个类可能就是你已经建议的那个:

http://www.entityframeworktutorial.net/entity-relationships.aspx

情况#3:我不知道我们在谈论什么样的实体,但如果实体A和B实际上是同一种实体,我会采用这种设计:

public class DependentEntity
{
    public int DependentEntityId { get; set; }
    public Nullable<int> EntityAId { get; set; }
    public Nullable<int> EntityBId { get; set; }
}

同样,这取决于你的情况。但对我来说,重要的是只有通过查看类的构造才能获得自己应用程序的抽象。

希望能帮助到你。


0
投票

你可以两种方式。 Ea或Eb,Ea和Eb。

这实际上取决于您的数据实际上是什么样的,以及出于何种目的。

当然,你不能为Ea和Eb都拥有相同的价值,因为这会破坏独立性,你将无法分辨哪个是哪个。

如果Ea和Eb都有相同的值,但是这个值是参考两个不同的东西,那么我就不会使用上面的设计了。因此,我将创建两个单独的列。

实际上将它们分开可能会更好,因为成本很低,如果发生数据损坏/输入错误,您将能够看到两列中的哪一列存在问题。

试试这个..

public class DependentEntity
{
    public int DependentEntityId { get; set; }
    public Nullable<int> EntityAOrBId { get; set; }
    public string EntityType { get; set; }
}

我希望有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.