【问题标题】:Entity Framework Core retrieving related entitiesEntity Framework Core 检索相关实体
【发布时间】:2020-05-28 22:32:25
【问题描述】:

我是 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 时遇到了错误。这是为什么?

【问题讨论】:

  • 尝试将public List&lt;Tool&gt; Tools { get; set; } 添加到您的Feature 课程中
  • @GuruStron,谢谢。我收到“路径解析器错误。/api/tool.get.responses.200.content.application/json.schema.properties.features.items.properties.tools.items.properties.features.items.$ref 无法解析如果我按照建议添加了工具列表,请大摇大摆地参考:未找到”。
  • 不确定是否与EF有关系=)

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


【解决方案1】:

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

所以你有多对多关系,你的表必须如下所示:

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 值!这里有什么错误吗?

【讨论】:

  • 谢谢! FeatureId 是一个错字。根据帖子,不是 List 不应该是功能中的 List 和 List 而不是工具中的 List 吗?当我这样做时: modelBuilder.Entity() .HasOne(t => t.Tool) .WithMany(f => f.Features) .HasForeignKey(t => t.ToolId);我在“.WithMany(f => f.Features)”处遇到错误:无法将类型“........List”隐式转换为“...IEnumerable”。无法将 lambda 表达式转换为预期的委托类型
  • 只需将 List<..> 替换为 ICollection<...> 这是我的错误 :)
猜你喜欢
  • 2018-02-27
  • 2020-08-06
  • 1970-01-01
  • 1970-01-01
  • 2020-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多