我正在试图找出处理简单问题的最佳方法: 我有一个简单的LINQ连接到两个表。我知道如何返回一个表的类型,因为它与生成的dbml类相同。但是,如果我想从两个表中返回数据怎么办?是不是有办法返回两者并使用它们的关系?我是否真的必须创建另一个返回类型以从两个表返回数据?仅供参考 - 我不想用另一个表对象返回输出参数;我对返回匿名类型也不是很感兴趣。什么是最佳做法推荐?
public IQueryable<Consumer_Question> GetQuestions(int subCategoryId)
{
//create DataContext
MototoolsDataContext mototoolsDataContext = new MototoolsDataContext();
mototoolsDataContext.Log = Console.Out;
var subcategoriestag = (from subCatTag in mototoolsDataContext.Consumer_SubCategoriesTags
join tagQuestion in mototoolsDataContext.Consumer_TagQuestions on subCatTag.TagID equals tagQuestion.TagID
join question in mototoolsDataContext.Consumer_Questions on tagQuestion.QuestionsID equals question.ID
where subCatTag.SubCategoriesID == subCategoryId
orderby subCatTag.ID descending
select question);
//select new { question, tagQuestion });
return subcategoriestag;
}
感谢您的帮助,
答案 0 :(得分:1)
如果您已经在LINQ-to-SQL设计器中定义了关系,那么您的上述查询根本不需要连接语法,只需根据需要“走树”,例如:
var subCategoriesTag = (
from subCatTag in motoToolsDataContext
from tagQuestion in subCatTag.TagQuestions
from question in tagQuestion
where subCatTag.SubCategoriesID == subcategoryId
orderby subCatTag.ID descending
select question
);
请注意,第2个和第3个'from'语句使用的是上一个对象,因为LINQ-to-SQL应该已经知道了这个关系。
如果不了解您的关系,就很难给出更准确的答案。我不得不对相关属性做出一些假设。
答案 1 :(得分:0)
听起来像你正在寻找的是DataLoadOptions.LoadWith&lt;&gt;。这样您就可以返回Question对象,并通过定义的关联同时填充相关对象。像这样:
public IQueryable<Consumer_Question> GetQuestions(int subCategoryId)
{
//create DataContext
using (MototoolsDataContext mototoolsDataContext = new MototoolsDataContext())
{
mototoolsDataContext.Log = Console.Out;
DataLoadOptions options = new DataLoadOptions();
options.LoadWith<Consumer_Questions>(q => q.Consumer_TagQuestions);
options.LoadWith<Consumer_TagQuestions>(tag => tag.Consumer_SubCategoriesTags);
mototoolsDataContext.LoadOptions = options;
var questions = (from subCatTag in mototoolsDataContext.Consumer_SubCategoriesTags
join tagQuestion in mototoolsDataContext.Consumer_TagQuestions on subCatTag.TagID equals tagQuestion.TagID
join question in mototoolsDataContext.Consumer_Questions on tagQuestion.QuestionsID equals question.ID
where subCatTag.SubCategoriesID == subCategoryId
orderby subCatTag.ID descending
select question);
//select new { question, tagQuestion });
return questions;
}
}