简体   繁体   English

实体框架核心中的一对多关系

[英]One to many relation in Entity Framework Core

I have two tables News and Comments . 我有两个表NewsComments The Comments table has two foreign key columns UserId and NewsId . Comments表具有两个外键列UserIdNewsId

When I get a News item by id in Entity Framework Core, comments are null. 当我在Entity Framework Core中按ID获取News项时,评论为null。

News model class: 新闻模型类:

public partial class News
{
    public News()
    {
        NewsComments = new HashSet<NewsComments>();
        NewsLikes = new HashSet<NewsLikes>();
    }

    public int Id { get; set; }
    public string Title { get; set; }
    public string Text { get; set; }
    public string Thumbnail { get; set; }
    public string Image { get; set; }
    public DateTime? Date { get; set; }
    public int CategoryId { get; set; }
    public int PublisherId { get; set; }
    public int? ViewCount { get; set; }
    public int? LikeCount { get; set; }
    public int? CommentCount { get; set; }

    public virtual NewsCategories Category { get; set; }
    public virtual NewsPublishers Publisher { get; set; }
    public virtual ICollection<NewsComments> NewsComments { get; set; }
    public virtual ICollection<NewsLikes> NewsLikes { get; set; }
}

Comments model class: 评论模型类:

public partial class NewsComments
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public int NewsId { get; set; }
    public string Text { get; set; }
    public DateTime? Date { get; set; }
    public bool? IsAccept { get; set; }

    public virtual News News { get; set; }
    public virtual Users User { get; set; }
}

Get news method: 获取新闻方法:

public News GetNews(int id)
{
    return _db.News.Find(id);
}

In EF if you are set by default with eager loading so you need to include the model property of the relationship like so : 在EF中,如果您默认设置为预先加载,那么您需要像下面这样包含关系的model属性:

public News GetNews(int id)
{
    return _db.News.Include(n=>n.NewsComments).Find(id);
}

Unless you have have forced to lazy load but still you have to setup the relationship on the context 除非您被迫延迟加载,但仍然必须在上下文中设置关系

modelBuilder.Entity<NewsComments>(entity =>
{
    entity.HasOne(nc => nc.News)
    .WithMany(n => n.NewsComments)
    .HasForeignKey(nc => nd.NewsId);
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM