【发布时间】: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=> p.PostedDate).FirstOrDefault(); } }this.Posts 而不是this.Post -
哎呀,你是对的...为了简洁起见,我刚刚删除了大部分代码,并且有一些拼写错误。
标签: asp.net entity-framework entity-framework-core