【问题标题】:One to many relation in Entity Framework CoreEntity Framework Core 中的一对多关系
【发布时间】:2019-07-26 22:46:15
【问题描述】:

我有两张桌子NewsCommentsComments 表有两个外键列UserIdNewsId

当我在 Entity Framework Core 中通过 id 获得 News 项目时,cmets 为空。

新闻模型类:

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

【问题讨论】:

  • _db.News.Include(w => w.NewsComment).Find(id) 。如果我的语法错误,请自行修复。总之,您将需要使用 Include() :)
  • @Md.TazbirUrRahmanBhuiyan 'IIncludableQueryable>' 不包含“Find”的定义,并且没有可访问的扩展方法“Find”接受类型为“IIncludableQueryable>' 可以找到(您是否缺少 using 指令或程序集引用?)
  • 您将不得不使用 Where() 而不是 Find,因为 Inlcude() 返回 IQuerable() 对象
  • @Md.TazbirUrRahmanBhuiyan 输出:预期为 ',' 而不是 ''
  • @Md.TazbirUrRahmanBhuiyan pasteboard.co/IpLMslV.jpg

标签: c# asp.net


【解决方案1】:

如果您在 EF 中默认设置为预先加载,那么您需要像这样包含关系的模型属性:

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

【讨论】:

    猜你喜欢
    • 2017-02-17
    • 2019-08-07
    • 2020-03-12
    • 1970-01-01
    • 2020-12-09
    • 2021-04-09
    • 1970-01-01
    • 2017-06-02
    • 2022-12-10
    相关资源
    最近更新 更多