公共类ForumTopic { public Guid ForumTopicId {get;组; } public Guid OwnerId {get;组; } public Guid CategoryId {get;组; } public DateTime CreatedDate {get;组; } public string主题{get;组; } public bool IsSticky {get;组; } public bool IsClosed {get;组; } public int ViewCount {get;组; } public int TotalComments {get;组; } 公众评论LastComment {get;组; } }
然后我有一个Linq查询,我需要弄清楚如何填充LastComment,我不能创建一个新的ForumTopic因为Linq告诉我这是违反规则......
IQueryable<ForumTopic> query = from topic in context.ForumTopics
join comment in context.Comments on topic.ForumTopicId equals comment.TargetId into topicComments
from lastComment in topicComments.DefaultIfEmpty().OrderByDescending(c => c.CreatedDate).Take(1)
orderby topic.IsSticky, topic.CreatedDate descending
select topic;
查询返回SQL中正确的所有内容,但topic.LastComment为null。
有什么想法吗?
答案 0 :(得分:1)
主要问题是你没有分配LastComment。如果没有在数据库中建立关系,它就不知道如何填充该对象。
您需要手动分配评论:
IQueryable<ForumTopic> query = from topic in context.ForumTopics
orderby topic.IsSticky, topic.CreatedDate descending
select new ForumTopic
{
ForumTopicId = topic.ForumTopicId,
OwnerId = topic.OwnerId,
// .. etc
LastComment = topic.Comments.OrderByDescending(c => c.CreatedDate).FirstOrDefault();
};
显然,我假设你在主题和评论之间有一个亲子关系。如果不这样做,您应该重新考虑如何使用linq:p