[英]Entity Framework Core retrieving related entities
I'm new to EFC and was hoping to get some help with a problem I ran into.我是 EFC 的新手,希望能在遇到的问题上得到一些帮助。 Suppose I have two tables:假设我有两张桌子:
Tool table:工具表:
Version FeatureId
1 1
1 2
1 4
2 1
FeatureId Name
1 feature1
2 feature2
3 feature3
4 feature4
and based on these two tables I have the following:并基于这两个表,我有以下内容:
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; }
}
so a tool version may include more than one features and a feature may be included in more than one version.因此,一个工具版本可能包含多个功能,并且一个功能可能包含在多个版本中。 When I tried to retrieve a tool based on the version number like this:当我尝试根据版本号检索工具时,如下所示:
_context.Tool.Where(x => x.Version == versionID)
.Include(i => i.Features)
.ToList()
I ran into an error asking for a ToolId.我遇到了一个错误,要求提供 ToolId。 Why is that?这是为什么?
a tool version may include more than one features and a feature may be included in more than one version.一个工具版本可能包含多个功能,并且一个功能可能包含在多个版本中。
So you have many-to-many relashionship, and your tables must look like below:所以你有多对多的关系,你的表必须如下所示:
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; }
}
And the missed one:而错过的一个:
public class ToolsFeatures
{
public int ToolId { get; set; }
public Tool Tool { get; set; }
public int FeatureId { get; set; }
public Feature Feature { get; set; }
}
Then configure the relashions the dbcontext:然后在 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);
}
See Many-to-Many relashions查看多对多关系
Notice: You have FeatureId
defined as string
but it has int
values?注意:您将FeatureId
定义为string
,但它具有int
值? is there any mistake here?这里有什么错误吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.