0

I have an entity that excludes entities of the same type under certain conditions. In order to achieve this, I have an entity class like:

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);
}

This causes in EF creating a third column and foreign key field called Entity_ID in my model. Seems like it thinks I have another relationship defined here but I don't understand why.

Here is the part related to foreign keys in the tables created:

.ForeignKey("dbo.Entities", t => t.EntityID)
.ForeignKey("dbo.Entities", t => t.ExcludedEntityID)
.ForeignKey("dbo.Entities", t => t.Entity_ID)
Farhad Alizadeh Noori
  • 2,276
  • 17
  • 22

1 Answers1

0

This post helped me find the answer.

Basically, EF cannot have two foreign keys to the same entity field. If you need to create two foreign key to the same entity you should bind them to different fields. So in this example:

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

and this configuration:

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);
}

would solve the problem.

Community
  • 1
  • 1
Farhad Alizadeh Noori
  • 2,276
  • 17
  • 22