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

时间:2019-07-26 12:46:33

标签: c# asp.net

我有两个表NewsCommentsComments表具有两个外键列UserIdNewsId

当我在Entity Framework Core中通过ID获得News项时,注释为空。

新闻模型类:

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; }
}

评论模型类:

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; }
}

获取新闻方法:

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

1 个答案:

答案 0 :(得分:0)

在EF中,如果默认设置是急切加载,则需要像这样包含关系的model属性:

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

除非您被迫延迟加载,但仍然必须在上下文中设置关系

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