EF 7 beta 6:EF 7中具有一对多关系的实体

我有一个非常简单的模型:

class Bag { public int Id { get; set; } public ICollection RandomThings { get; set; } } class RandomThing { public int Id { get; set; } public String Description{ get; set; } } 

我的上下文的OnModelCreating (在EF 6中 )类似于:

 protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity() .ToTable("Bag") .HasMany(x => x.RandomThings).WithRequired(x => x.Bag).WillCascadeOnDelete(); modelBuilder.Entity().ToTable("RandomThing"); } 

据我所知,没有相同的方法可以做到这一点。 我知道不支持级联删除 。 但是,我想知道,在我的代码示例中定义的一对多关系建模的最佳方法是什么? 似乎所有这些东西已经消失(或者尚未实施)。

我已经看到了一个DbContext的示例( 这里 ),就像我想要的那样,但它实际上是错误的并且不起作用。 如果我尝试下载该源代码,设置我的环境,并在带有post的博客实体上进行保存,那些post就不会像人们想象的那样得到保存。

这有什么变通方法吗?

更新 :这个答案是为EF7 beta7编写的。 API已经改变了。 有关使用EF Core的最新信息,请参见http://docs.efproject.net/en/latest/modeling/relationships.html 。

原始答案

在EF 7中,您可以在OnModelCreating方法中配置一对多关系。 为此,请将属性添加到R​​andomThing以表示forign键,以及对父类型的CLR引用。

 class Bag { public int Id { get; set; } public ICollection RandomThings { get; set; } } class RandomThing { public int Id { get; set; } public String Description{ get; set; } public Bag Bag { get; set; } public int BagId { get; set; } } 

在您的上下文中,使用以下设置配置关系:

 protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .Reference(e => e.Bag) .InverseCollection(p => p.RandomThings) .ForeignKey(e => e.BagId); } 

附注 :当EF 7 计划添加对通过属性进行配置的支持时 。

虽然我根本没有使用EF7,但在EF6中,我会让你的模型看起来像这样:

 class Bag { public int Id { get; set; } public virtual ICollection RandomThings { get; set; } } class RandomThing { public int Id { get; set; } public String Description{ get; set; } public int BagId {get; set;} [ForeignKey("BagId")] Public Bag Bag {get; set;} } 

通过这种方式,可以使用数据注释来处理关系,并且您不需要针对此特定任务的model builder