首页 > 其他 > 详细

EF Core导航属性

时间:2019-10-31 10:42:40      阅读:185      评论:0      收藏:0      [点我收藏+]

原文地址:https://www.jianshu.com/p/c6896a651cfb

EF Core导航属性分为三种:
集合导航属性:主表中对子表相关数据的引用
引用导航属性:子表中对主表数据的引用
反转导航属性:一个导航属性对应的另一端的导航属性
微软的示例:
Blog是主表,Post是子表

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

在以上实体类的定义中:
Blog.Posts是集合导航属性,包含子表中的关联数据。
Post.Blog是引用导航属性,包含主表中的关联数据。
Post.Blog是Blog.Posts的反转导航属性,反过来也一样。
通过子表查询主表数据:
var post=db.Posts.Include("Blog").First();
可以访问到Blog表的其它字段:
Console.Write(post.Blog.Url)
通过主表访问子表数据:
var blog=db.Blogs.Include(b=>b.Posts).First();
可以访问子表相关的所有数据:

foreach(var post in blog.Posts)
{
    Console.Write(post.Title);
}

通过引用导航属性访问主表数据,不需要额外定义。
通过集合导航属性访问子表数据,需要使用Fluent API配置。重写数据上下文的OnModelCreating方法,加入以下代码:

builder.Entity<Post>()
        .HasOne(post => post.Blog)
        .WithMany(bolg => blog.Posts);

如果不使用Fluent API进行配置,执行var blog=db.Blogs.Include(b=>b.Posts).First();时会报数据库语法错误。

EF Core导航属性

原文:https://www.cnblogs.com/dawenxi0/p/11769819.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!