簡體   English   中英

實體框架核心中的一對多關系

[英]One to many relation in Entity Framework Core

我有兩個表NewsComments Comments表具有兩個外鍵列UserIdNewsId

當我在Entity Framework Core中按ID獲取News項時,評論為null。

新聞模型類:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM