EF一对多关系

时间:2020-03-17 16:17:46

标签: asp.net-core entity-framework-core

我有一个Section对象,它与两个Node对象完全相关。基本上,Section对象是具有起点和终点的路线。我找不到关于多对多关系的很多东西,我什至不知道这是否有事。

public class Section
{
    public Guid Id { get; set; }
    public int Length { get; set; }

    public Node StartNode { get; set; }
    public Guid StartNodeId { get; set; }
    public Node EndNode { get; set; }
    public Guid EndNodeId { get; set; }
}


public class Node
{
    public Guid Id { get; set; }
    public string Name { get; set; }

    public ICollection<Section> Sections { get; set; }
}

这不行:

modelBuilder.Entity<Section>()
            .HasOne(se => se.StartNode)
            .WithMany(sn => en.Sections)
            .HasForeignKey(se => se.StartNodeId);

modelBuilder.Entity<Section>()
            .HasOne(se => se.EndNode)
            .WithMany(en => en.Sections)
            .HasForeignKey(se => se.EndNodeId);

我应该将此映射为多对多关系吗?我想从一个节点访问节,并从我的节中访问两点。

1 个答案:

答案 0 :(得分:0)

您真正想要的是多个具有相同实体的one-to-many

因此您的Node类应如下所示:

public class Node
{
    public Guid Id { get; set; }
    public string Name { get; set; }

    public ICollection<Section> StarNodeSections { get; set; }
    public ICollection<Section> EndNodeSections { get; set; }
}

然后在 Fluent API 配置中进行如下操作:

modelBuilder.Entity<Section>()
            .HasOne(se => se.StartNode)
            .WithMany(sn => sn.StarNodeSections) // <--  Here it is
            .HasForeignKey(se => se.StartNodeId)
            .OnDelete(DeleteBehavior.Restrict);

modelBuilder.Entity<Section>()
            .HasOne(se => se.EndNode)
            .WithMany(en => en.EndNodeSections) // <--  Here it is
            .HasForeignKey(se => se.EndNodeId)
            .OnDelete(DeleteBehavior.Restrict);