【问题标题】:Navigation Property returns null?导航属性返回 null?
【发布时间】:2018-11-07 06:59:43
【问题描述】:
class Topic {
   public int TopicId {get;set;}
   public virtual ICollection<Post> Posts { get; set; }
   public Post FirstPost { 
      get {
         return this.Posts.OrderBy(p=> p.PostedDate).FirstOrDefault();
      }
   }
}

class Post {
    public int PostId {get;set; }
    public int TopicId {get;set;}
    public DateTime PostedDate {get;set;}

    public virtual Topic Topic {get;set;}
}


var query = Database.Forums.Where(p=> p.Id == id).Select(p=> new  {
   p.Title,
   Topics = p.Topics.OrderByDescending(p=> p.LastPostedDate).Select(t=> new  {
       t.TopicId,
       t.FirstPost.PostId
   })
}).ToList();

当我运行此查询时,t.FirstPost 为空,即使该主题在数据库中确实有帖子。有没有办法使用导航属性而不是使用查询语法和连接来做到这一点?

【问题讨论】:

  • 这不应该像public Post FirstPost { get { return this.Posts.OrderBy(p=&gt; p.PostedDate).FirstOrDefault(); } }this.Posts 而不是this.Post
  • 哎呀,你是对的...为了简洁起见,我刚刚删除了大部分代码,并且有一些拼写错误。

标签: asp.net entity-framework entity-framework-core


【解决方案1】:

我认为您需要将代码从 this.Post 更新到 this.Posts like this

public Post FirstPost { 
      get {
         return this.Posts.OrderBy(p=> p.PostedDate).FirstOrDefault();
      }
   }

【讨论】:

  • 在get方法中放一个断点,检查this.Posts是否有post实体
【解决方案2】:

通常避免在 LINQ to Entities 查询中使用未映射的属性。它们无法转换为 SQL,即使 EF Core 支持客户端评估,访问导航属性也是有问题的,因为它们在评估发生时尚未加载。

您可以在 LINQ to Entities 查询中使用导航属性(这实际上比显式连接更可取),但使用显式 表达式,即不隐藏在未映射的属性后面:

var query = Database.Forums.Where(f => f.Id == id).Select(f => new
{
   f.Title,
   Topics = f.Topics.OrderByDescending(t => t.LastPostedDate).Select(t => new
   {
       t.TopicId,
       FirstPostId = Posts.OrderBy(p => p.PostedDate).Select(p => (int?)p.PostId).FirstOrDefault(),
   })
}).ToList();

(不确定LastPostedDate 是什么 - 它没有显示在发布的模型中,希望不是另一个未映射的属性。但你明白了)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    • 2023-01-20
    相关资源
    最近更新 更多