Entity framework core 如何在EF 7 alpha中添加外键

Entity framework core 如何在EF 7 alpha中添加外键,entity-framework-core,Entity Framework Core,如何在EF 7 alpha3中建立一对一的关系 仅定义导航属性的旧方法不起作用,并且modelBuilder没有以前使用的HasRequired/HasOptional方法 有人能解释一下吗?直到最近,还没有任何用于定义关系的模型生成器API。相反,您必须操作底层的modelBuilder.Model对象。以下是一对多关系的示例 class博客 { 公共博客() { Posts=新列表(); } 公共int Id{get;set;} 公共ICollection Posts{get;set;} }

如何在EF 7 alpha3中建立一对一的关系

仅定义导航属性的旧方法不起作用,并且modelBuilder没有以前使用的HasRequired/HasOptional方法


有人能解释一下吗?

直到最近,还没有任何用于定义关系的模型生成器API。相反,您必须操作底层的
modelBuilder.Model
对象。以下是一对多关系的示例

class博客
{
公共博客()
{
Posts=新列表();
}
公共int Id{get;set;}
公共ICollection Posts{get;set;}
}
班岗
{
公共int Id{get;set;}
public int BlogId{get;set;}
公共博客Blog{get;set;}
}
类BlogContext:DbContext
{
公共数据库集博客{get;set;}
公共DbSet Posts{get;set;}
模型创建时受保护的覆盖无效(ModelBuilder)
{
builder.Entity().ForeignKey(x=>x.ForeignKey(p=>p.BlogId));
var model=builder.model;
var blog=model.GetEntityType(typeof(blog));
var post=model.GetEntityType(typeof(post));
var fk=post.ForeignKeys.Single(k=>k.referencedentitype==blog);
AddNavigation(新导航(fk,“Posts”,pointsToPrincipal:false));
post.AddNavigation(新导航(fk,“Blog”,pointsToPrincipal:true));
}
}
您可以阅读更多关于我们当前(截至2014年7月31日)的思考。最终结果如下所示

modelBuilder.Entity()
.OneToMany(b=>b.Posts,p=>p.Blog).ForeignKey(b=>b.BlogId);

使用EF7 beta7,引入了一组新的方法来定义实体之间的关系

对于一对多关系

modelBuilder.Entity<Post>()
   .Reference(typeof(Blog), "Blog")
   .InverseCollection("Posts")
   .ForeignKey(new string[] { "BlogId" });
modelBuilder.Entity()
.参考(博客类型),“博客”)
.逆向收款(“员额”)
.ForeignKey(新字符串[]{“BlogId”});
使用,
.Reference(typeof(Blog),“Blog”)
配置从实体
Post
Blog
的关系。第一个参数是Post目标实体的类型,第二个参数是导航属性的名称

使用,
.InverseCollection(“Posts”)
,可以配置一对多关系。此函数的参数是导航集合的名称


使用,
.ForeignKey(新字符串[]{“BlogId”})
,配置外键。如果未设置此外键,则会自动为您生成阴影外键。

我使用的是EF7 beta3,实体没有ForeignKeys属性。还有一个,一个,一个,一个,还有一个都还没找到。目前在EF7中是否还有其他可能存在一对多/多对一关系?我使用Entity().HasMany().WithOne().ForeignKey()-语法取得了一些成功。即使引用的父模型(“Blog”)保持为空,至少自定义外键(不是“BlogId”,而是“SomethingOtherId”)可以正常工作。以前我得到了“BlogId”列“找不到错误”。它都不见了。EF7 beta7。@希米,你知道在EF7 beta7中哪里可以找到这些方法吗?我找不到它。