[英]Entity Framework Core retrieving related entities
我是 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 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 中配置 relashions:
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);
}
查看多对多关系
注意:您将FeatureId
定义为string
,但它具有int
值? 这里有什么错误吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.