通过一个Linq-to-Sql查询检索多个表

时间:2013-07-10 16:36:27

标签: c# linq-to-sql

目前,我正在使用三个数据库查询在我的MVC应用程序中填充模型。

这是怎么回事:

IndexViewModel model = new IndexViewModel();

model.Links = Repository.GetAll().ToArray();
model.SourceOne = StaffMembersRepository.GetAll().ToArray();
model.SourceTwo = CategoriesRepository.GetAll().ToArray();

return model;

我希望只做一个查询(为了更好的性能),它应该返回三个表的所有行。

我不能去内连接,因为这三个表根本没有连接(假设它们没有连接)。

我试过

var result = from link in Repository.GetAll()
             from staffMember in StaffMembersRepository.GetAll()
             from category in CategoriesRepository.GetAll()
             select new { link, staffMember, category };

但是有一个编译错误突出显示“CategoriesRepository.GetAll()”代码段:

  

源类型为“System.Linq.IQueryable”的查询表达式中的后续from子句中不允许使用类型为“System.Linq.IQueryable”的表达式。调用“SelectMany”时类型推断失败。

无论那意味着什么。

2 个答案:

答案 0 :(得分:0)

使用DataLoadOptions类的LoadWith方法生成单个查询,如果可以通过外键关系对其进行Linq-ed,则可以在其中加载所有相关数据,请阅读更多here

如果没有这样的关系,那么您可以使用DataContext实现连接查询: 在此处阅读更多内容:Simple Examples of joining 2 and 3 table using lambda expression

答案 1 :(得分:0)

我认为一次性通过LINQ检索完全不相关的表是不可能的。可能出于性能原因,您应该考虑缓存,这样您就不需要每次都查询数据库。

使用MSSQL上的纯SQL,您可以使用批处理语句。

var batchSql = "select * from Repository; select * from StaffMembersRepository; select * from CategoriesRepository";
// ...
// iterate over batch results
using(var reader = command.ExecuteReader())
{
    var currentResultSet = 0;
    while(reader.NextResult())
    {
        currentResultSet++;
        switch(currentResultSet)
        {
            case 1:
                while(reader.Read())
                {
                    // retrieve row data
                }
            case 2:
                // similar
            case 3:
                // similar
        }
    }
}

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.nextresult.aspx

但我认为这不是一个好方法。