如何在EF中配置一对多关系 [英] How to configure a One-to-Many relationship in EF
问题描述
我有以下型号
public class PageConfig : Base
{
// Properties Etc..
public ICollection<Image> ScrollerImages { get; set; }
}
我的方法是使用联结表{PageConfigID,ImageID}进行绑定.
My approach is to bind using a junction table { PageConfigID, ImageID }.
在我的模型资料夹中,我尝试了以下方法.
In my model binder i tried the following..
modelBuilder.Entity<PageConfig>()
.HasMany(x => x.ScrollerImages)
.WithMany()
.Map(x =>
{
x.ToTable("junc_PageConfigScrollerImages");
x.MapLeftKey("PageConfigID");
x.MapRightKey("ImageID");
});
这将导致图像的空集合.
Which results in a null collection of images.
如何将这些图像绑定到PageConfig模型?
How can i bind these Images to the PageConfig model?
编辑
大多数问题是由于用户错误引起的. jic这发生在你身上.
Most of the problem was due to user error. jic this happens to you..
检查是否正确设置了数据库中的关键约束.
模型上的ICollection需要为虚拟的.
Check that the key constraints in the database are correctly set.
The ICollection on the model NEEDS to be virtual.
推荐答案
如果要在这两个实体之间建立一对多关系,则模型将如下所示:
If you want to create an one-to-many relationship between those two entities your model would be like this:
public class PageConfig
{
public int Id {get;set;}
//navigation property
public ICollection<Image> ScrollerImages {get;set;}
}
public class Image
{
public int Id {get;set;}
//FK
public int? PageConfigId {get;set;}
//navigation property
public PageConfig PageConfig {get;set;}
}
Fluent Api的配置应为:
And the Fluent Api configuration would be:
modelBuilder.Entity<Image>()
.HasOptional(i=>i.PageConfig)
.WithMany(pc=>pc.ScrollerImages)
.HasForeignKey(i=> i.PageConfigId);
如果您想创建一个单向一对多关系,则删除Image
实体上的FK和导航属性,并通过以下方式配置该关系:
If you idea is create an unidirectional one-to-many relationship then delete the FK and the navigation property on Image
entity and configure the relationship this way:
modelBuilder.Entity<PageConfig>()
.HasMany(pc => pc.ScrollerImages)
.WithOptional();
检查此链接以获取更多信息关于这种关系
Check this link for more info about this kind of relationship
这篇关于如何在EF中配置一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!