0

我有一个实体在某些条件下排除了相同类型的实体。为了实现这一点,我有一个实体类,如:

public class Entity
{
    public int ID { get; set; }
    public virtual ICollection<EntityExcludedEntity> ExcludedEntities { get; set; }
}

public class ExcludedEntity
{
    public int ID { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; }

    public int EntityID { get; set; }
    public virtual Entity Entity { get; set; }

    public int ExcludedEntityID { get; set; }
    public virtual Entity ExcludedEntity { get; set; }
}

//declared in the ExcludedEntity mapping class.
public ExcludedEntityMapping()
{
    HasRequired(t => t.Entity).WithMany(t => t.ExcludedEntity).HasForeignKey(t => t.EntityID)
    HasRequired(t => t.ExcludedEntity).WithMany(t => t.ExcludedEntity).HasForeignKey(t => t.ExcludedEntityID);
}

这会导致在 EF 中创建Entity_ID在我的模型中调用的第三列和外键字段。似乎它认为我在这里定义了另一种关系,但我不明白为什么。

以下是创建的表中与外键相关的部分:

.ForeignKey("dbo.Entities", t => t.EntityID)
.ForeignKey("dbo.Entities", t => t.ExcludedEntityID)
.ForeignKey("dbo.Entities", t => t.Entity_ID)
4

1 回答 1

0

这篇文章帮助我找到了答案。

基本上,EF 不能有两个外键指向同一个实体字段。如果您需要为同一实体创建两个外键,则应将它们绑定到不同的字段。所以在这个例子中:

public class Entity
{
    public int ID { get; set; }
    public virtual ICollection<EntityExcludedEntity> ExcludingEntities { get; set; }
    public virtual ICollection<EntityExcludedEntity> ExcludedFromEntities { get; set; }
}

和这个配置:

public DBConceptAnswerExcludedAnswerMapping()
{
    HasRequired(t => t.Entity).WithMany(t => t.ExcludingEntities).HasForeignKey(t => t.EntityID);
    HasRequired(t => t.ExcludedEntity).WithMany(t => t.ExcludedFromEntities).HasForeignKey(t => t.ExcludedEntityID);
}

将解决问题。

于 2015-04-23T14:12:14.377 回答