Linq to sql Linq到SQL过滤关联?

Linq to sql Linq到SQL过滤关联?,linq-to-sql,Linq To Sql,公共课主题 { UMTopicid{get;set;}的公共Guid 公共Guid所有者ID{get;set;} 公共Guid类别ID{get;set;} 公共日期时间CreatedDate{get;set;} 公共字符串主题{get;set;} 公共布尔值为{get;set;} 公共布尔是封闭的{get;set;} public int ViewCount{get;set;} 公共int TotalComments{get;set;} 公共注释LastComment{get;set;} }

公共课主题 { UMTopicid{get;set;}的公共Guid 公共Guid所有者ID{get;set;} 公共Guid类别ID{get;set;} 公共日期时间CreatedDate{get;set;} 公共字符串主题{get;set;} 公共布尔值为{get;set;} 公共布尔是封闭的{get;set;} public int ViewCount{get;set;} 公共int TotalComments{get;set;} 公共注释LastComment{get;set;} }


然后我有一个Linq查询,我需要弄清楚如何填充最后的注释,我不能创建一个新的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;
IQueryable query=来自context.ForumTopics中的主题
在上下文中加入注释。topic.ForumTopicId上的注释等于comment.TargetId到topicComments中
从topicComments.DefaultIfEmpty().OrderByDescending(c=>c.CreatedDate)中的lastComment。获取(1)
orderby topic.IsSticky,topic.CreatedDate降序
选题;
查询返回SQL中所有正确的内容,但topic.lastcoment为null


有什么想法吗?

主要问题是您没有指定最后一条评论。如果数据库中没有建立关系,它就不知道如何填充该对象

您需要手动分配注释:

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();
};
IQueryable query=来自context.ForumTopics中的主题
orderby topic.IsSticky,topic.CreatedDate降序
选择新论坛主题
{
ForumTopicId=topic.ForumTopicId,
OwnerId=topic.OwnerId,
//等等
LastComment=topic.Comments.OrderByDescending(c=>c.CreatedDate.FirstOrDefault();
};

显然,我假设你在主题和评论之间有一种父子关系。如果不这样做,您应该重新考虑如何使用linq:p

,正如JustLoren所说,您的linq查询是不正确的。我认为JustLoren的查询是您可能需要的。我有:在上下文中连接comment。topic.ForumTopicId上的Comments等于comment.TargetId到其中的topicComments,这就是关系。我尝试了新的ForumTopic{}东西,但Linq告诉我这是禁止的,可能是因为ForumTopic是Linq to SLQ在我的mapping.xml中映射的类型。还有其他想法吗?@Bryan:我想你是在用L2S的设计师。我不熟悉mapping.xml实现。当我指的是关系时,我指的是在模式中,而不是在select语句中。Linq的一个巨大好处是它管理对象关系的方式,并允许您对它们进行查询。我不知道为什么你的编译器抱怨它被禁止了——在网上有很多例子,L2S类型被实例化并作为select命令的一部分显式填充。mapping.xml是否为LastComment定义了映射?如果是,是什么?