如何在EF 7 Alpha中添加外键 [英] how to add foreign keys in EF 7 alpha
问题描述
如何在EF 7 alpha3中建立一对一关系?
How do I make a one-to-one relationship in EF 7 alpha3?
仅定义导航属性的旧方法不起作用,而ModelBuilder可以没有以前使用过的HasRequired / HasOptional方法。
The old way of just defining navigation properties does not work, and the modelBuilder does not have the previously used HasRequired/HasOptional methods.
有人可以对此有所了解吗?
Can anyone shed some light on that?
推荐答案
直到最近,还没有用于定义关系的任何模型构建器API。相反,您必须操作基础的 modelBuilder.Model
对象。这是一对多关系的示例。
Until recently, there weren't any model builder APIs for defining relationships. Instead, you have to manipulate the underlying modelBuilder.Model
object. Here is an example of a one-to-many relationship.
class Blog
{
public Blog()
{
Posts = new List<Post>();
}
public int Id { get; set; }
public ICollection<Post> Posts { get; set; }
}
class Post
{
public int Id { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
class BlogContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Post>().ForeignKeys(x => x.ForeignKey<Blog>(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.ReferencedEntityType == blog);
blog.AddNavigation(new Navigation(fk, "Posts", pointsToPrincipal: false));
post.AddNavigation(new Navigation(fk, "Blog", pointsToPrincipal: true));
}
}
您可以阅读更多有关我们当前的信息(截至2014年) -07-31)思考这些API的外观。最终结果如下所示。
You can read more about our current (as of 2014-07-31) thinking for what these APIs will look like. The end result would look something like the following.
modelBuilder.Entity<Blog>()
.OneToMany(b => b.Posts, p => p.Blog).ForeignKey(b => b.BlogId);
这篇关于如何在EF 7 Alpha中添加外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!