简体   繁体   English

EF一对多映射

[英]EF Mapping One To Many

I am trying to figure out how to map the following relationship: 我试图弄清楚如何映射以下关系:

  • The "Relation" entity requires a "Node" and a "RelatedNode". “关系”实体需要一个“节点”和一个“相关节点”。

  • The Node entity has a collection of "Relations" (HasMany), where the Node is required to be the Relation.Node OR Relation.RelatedNode. Node实体具有“关系”(HasMany)的集合,其中要求该节点为Relation.Node或Relation.RelatedNode。

The current mapping is resulting in a table that looks like this: 当前映射将生成一个如下表:

[Id],[NodeId],[RelatedNodeId],[RelationType],[Node_Id]

[Node_Id] is getting automatically created, and this is what I am trying to avoid. [Node_Id]是自动创建的,这就是我要避免的事情。

Relation Entity: 关系实体:

public class Relation
{
    private Relation()
    {

    }

    public Relation(int nodeId, int relatedNodeId)
    {
        NodeId = nodeId;
        RelatedNodeId = relatedNodeId;
    }

    public Relation(Node node, Node relatedNode)
    {
        Node = node;
        RelatedNode = relatedNode;
    }

    public int Id { get; set; }

    public int NodeId { get; set; }

    public Node Node { get; set; }

    public int RelatedNodeId { get; set; }

    public Node RelatedNode { get; set; }

    public RelationType RelationType { get; set; }
}

Fluent-API: 流利的API:

// Relation
modelBuilder.Entity<Relation>().Map(m =>
{
    m.ToTable("Relations");
});
modelBuilder.Entity<Relation>()
    .HasKey(t => t.Id)
    .Property(t => t.Id)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<Relation>().HasRequired(t => t.Node).
    WithMany().HasForeignKey(t => t.NodeId).WillCascadeOnDelete(false);
modelBuilder.Entity<Relation>().HasRequired(t => t.RelatedNode).
    WithMany().HasForeignKey(t => t.RelatedNodeId).WillCascadeOnDelete(false);


// Node
modelBuilder.Entity<Node>().Map(m =>
{
    m.MapInheritedProperties();
    m.ToTable("Nodes");
});
modelBuilder.Entity<Node>().HasMany(t => t.Relations);

Remove this line 删除此行

modelBuilder.Entity<Node>().HasMany(t => t.Relations);

You've already specified this relationship above. 您已经在上面指定了此关系。


Entity Framework is adding that column to represent a relationship from Relation to Node. 实体框架正在添加该列以表示从关系到节点的关系。 Since you specify the HasForeignKey for "Node" and "RelatedNode", it creates the "NodeId" and "RelatedNodeId" columns (as you expect and want). 由于您为“ Node”和“ RelatedNode”指定了HasForeignKey,因此它会创建“ NodeId”和“ RelatedNodeId”列(如您所期望的那样)。

The "Node_Id" column is what EF would generate when it needs a FK that hasn't been specified. EF需要未指定的FK时,EF将生成“ Node_Id”列。 So, somewhere EF is being told that there is a relationship from Node to Relation and the FK is not being specified (EG the line removed) 因此,在某个地方,EF被告知存在从Node到Relation的关系,而未指定FK(例如,删除了该行的EG)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM