如何在EF 7 alpha3中建立一对一的关系?
仅定义导航属性的旧方法不起作用,并且modelBuilder没有以前使用的HasRequired / HasOptional方法。
有人可以对此有所了解吗?
答案 0 :(得分:2)
直到最近,还没有任何模型构建器API用于定义关系。相反,您必须操纵基础modelBuilder.Model
对象。以下是一对多关系的示例。
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));
}
}
您可以阅读有关what these APIs will look like的当前(截至2014-07-31)思考的更多信息。最终结果如下所示。
modelBuilder.Entity<Blog>()
.OneToMany(b => b.Posts, p => p.Blog).ForeignKey(b => b.BlogId);
答案 1 :(得分:0)
使用EF7 beta7,引入了一组新的方法来定义实体之间的关系。
对于一对多关系,
modelBuilder.Entity<Post>()
.Reference(typeof(Blog), "Blog")
.InverseCollection("Posts")
.ForeignKey(new string[] { "BlogId" });
配置从实体.Reference(typeof(Blog), "Blog")
到Post
的{{1}}关系。第一个论点是Post目标的实体类型,第二个论点是导航属性的名称。
使用Blog
配置一对多关系。这个函数的参数是导航集的名称。
使用.InverseCollection("Posts")
配置外键。如果未设置此外键,则会自动为您生成影子外键。