Chr*_*ris 5 entity-framework-core
如何在EF 7 alpha3中建立一对一的关系?
仅定义导航属性的旧方法不起作用,并且modelBuilder没有以前使用的HasRequired/HasOptional方法.
任何人都可以对此有所了解吗?
直到最近,还没有任何用于定义关系的模型构建器 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));
}
}
Run Code Online (Sandbox Code Playgroud)
您可以阅读更多关于我们当前(截至 2014 年 7 月 31 日)对这些 API 外观的思考。最终结果如下所示。
modelBuilder.Entity<Blog>()
.OneToMany(b => b.Posts, p => p.Blog).ForeignKey(b => b.BlogId);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7875 次 |
| 最近记录: |