简体   繁体   中英

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.

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.

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:

// 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).

The "Node_Id" column is what EF would generate when it needs a FK that hasn't been specified. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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