c# - 在 Entity Framework 7 中创建自引用的多对多关系

标签 c# entity-framework asp.net-core entity-framework-core

我正在尝试使用 Entity Framework 7 fluent API 设置我的数据库以添加自引用多对多关系。 有问题的类看起来像:

public class Definition
{
    // Some properties
    public virtual ICollection<Definition> AllowedChildDefinitions { get; set; }
}

其中预期的关系是每个定义都可以有任意数量的任何实例的子项。我希望有一个包含父/子列的单独表,其中每个父项可以有多个子项,每个子项可以在多个父项中。

有多对多的示例和自引用表的示例,但我不知道如何将两者结合起来。

最佳答案

解决方法是将连接表映射到一个实体。请调查一下。

public class Definition
{
   public int Id { get; set; }
   public ICollection<ChildrenDefinition> ChildrenDefinitions{ get; set; }
}

public class ChildrenDefinition
{
  public int DefinitionId { get; set; }
  public Definition Definition { get; set; }

  public int ChildrenId { get; set; }
  public Children Children { get; set; }
}

public class Children
{
    public int Id { get; set; }
    public ICollection<ChildrenDefinition> ChildrenDefinitions{ get; set; }
}

确保使用组合键配置 ChildrenDefinition:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<ChildrenDefinition>().HasKey(x => new {  x.DefinitionId, x.ChildrenId });
}

要导航,请使用选择:

// Children.Definition
var definitions = Children.ChildrenDefinitions.Select(c => c.Definition);

希望这对您有所帮助!

关于c# - 在 Entity Framework 7 中创建自引用的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37653514/

相关文章:

c# - ASP.NET Core 2.1 无效请求行问题

c# - Windows 服务的设计模式 - C#

c# - 连接到 Azure 云 Blob 存储失败,证书无效

asp.net-core - 如何在 .NET Core 3.1.x 上写入 HttpContext.Response.Body

c# - 是否可以将强类型数组绑定(bind)为 ASP.NET Core 中的配置模型?

entity-framework - EF 迁移错误 : could not load type 'System.Data.Entity.Infrastructure.DbContextInfo'

c# - api Controller 的文件下载问题

C#获取焦点所在的Windows资源管理器路径

c# - EntityFramework 和 aspnetdb

c# - 如何在linq中包含()嵌套子实体