多个表的EF核心外键

时间:2020-02-11 12:41:50

标签: sql entity-framework

假设我定义了与三个表相对应的以下三个实体,即Entity1Entity2Entity3

public class Entity1 {
    public Guid Id { get; set; }
    public string Foo { get; set; }
}

public class Entity2 {
    public Guid Id { get; set; }
    public string Bar { get; set; }
}

public class Entity2 {
    public Guid Id { get; set; }
    public int Boo { get; set; }
}

现在让我们说这些实体中的每一个都通过position属性相互关联,例如,位置属性提供列表中这些实体的顺序。为了存储该位置信息,我创建了另一个表EntityPosition,如下所示

public class EntityPosition {
    public Guid EntityId { get; set; }
    public int Position { get; set; }
}

其中EntityIdEntity1.IdEntity2.IdEntity3.Id的代理键,即EntityPosition表中的一个条目映射到其中一个三个实体。我想要进行设置,以便在添加新实体时可以按以下方式进行操作

var position = new EntityPosition {
    Position = 0
};

var entity = new Entity2{
    EntityPosition = position
};

context.Entity2.Add(entity);
context.SaveChanges();

,以使EF可以正确地为Entity2创建一个Guid ID,并将相同的ID分配给EntityId表中的EntityPosition。因此,我尝试如下将导航属性EntityPosition添加到每个实体表

public class Entity1 {
    public Guid Id { get; set; }
    public string Foo { get; set; }
    public EntityPosition EntityPosition { get; set; }
}

public class Entity2 {
    public Guid Id { get; set; }
    public string Bar { get; set; }
    public EntityPosition EntityPosition { get; set; }
}

public class Entity2 {
    public Guid Id { get; set; }
    public int Boo { get; set; }
    public EntityPosition EntityPosition { get; set; }
}

EntityPosition中的等效导航属性,即

public class EntityPosition {
    public Guid EntityId { get; set; }
    public int Position { get; set; }
    public Entity1 { get; set; }
    public Entity2 { get; set; }
    public Entity3 { get; set; }
}

然后我还为每个实体类添加了以下流利的配置

builder.HasOne(x => x.PathEntityPosition)
    .WithOne(x => x.Entity1)
    .HasForeignKey<PathEntityPosition>(x => x.EntityId);

builder.HasOne(x => x.PathEntityPosition)
    .WithOne(x => x.Entity2)
    .HasForeignKey<PathEntityPosition>(x => x.EntityId);

builder.HasOne(x => x.PathEntityPosition)
    .WithOne(x => x.Entity3)
    .HasForeignKey<PathEntityPosition>(x => x.EntityId);

但是,当我尝试添加具有位置的新实体时,我当前收到FK约束错误。尝试将单个表链接回多个表时,我是否设置正确?

0 个答案:

没有答案