实体框架核心检索相关实体

时间:2020-05-28 22:32:25

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

我是EFC的新手,希望能对遇到的问题获得帮助。 假设我有两个表:

工具表:

Version  FeatureId 

1         1

1         2

1         4

2         1

功能表:

FeatureId Name

1         feature1

2         feature2

3         feature3

4         feature4

,根据这两个表,我有以下内容:

public class Tool
{

public int Id {get; set;}

public int Version { get; set; } 

public List<Feature> Features { get; set; }

}

public class Feature
{

public string FeatureId { get; set; }

public string Name { get; set; }
}

因此,一个工具版本可能包含多个功能,而一个功能可能包含在多个版本中。当我尝试根据这样的版本号检索工具时:

_context.Tool.Where(x => x.Version == versionID)
           .Include(i => i.Features)
           .ToList()

我遇到一个错误,要求提供ToolId。这是为什么?

1 个答案:

答案 0 :(得分:0)

一个工具版本可能包含多个功能,而一个功能可能包含在多个版本中。

因此您拥有多对多的冲突,并且您的表必须如下所示:

public class Tool
{
    public int Id {get; set;}
    public int Version { get; set; } 
    public ICollection<Feature> Features { get; set; }
}

public class Feature
{
    public string FeatureId { get; set; }
    public string Name { get; set; }
    public ICollection<Tool> Tools { get; set; }
}

失踪者:

public class ToolsFeatures
{
    public int ToolId { get; set; }
    public Tool Tool { get; set; }

    public int FeatureId { get; set; }
    public Feature Feature { get; set; }
}

然后配置dbcontext的冲突:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ToolsFeatures>()
        .HasKey(t => new { t.ToolId, t.FeatureId});

        modelBuilder.Entity<ToolsFeatures>()
            .HasOne(t => t.Tool)
            .WithMany(f => f.Features)
            .HasForeignKey(t => t.ToolId);

        modelBuilder.Entity<ToolsFeatures>()
            .HasOne(f => f.Feature)
            .WithMany(t => t.Tools)
            .HasForeignKey(f => f.FeatureId);
    }

请参见Many-to-Many relashions


注意:您已将FeatureId定义为string,但它具有int值!这里有什么错误吗?