来自不同数据库的查询,仅支持原始类型或枚举类型

时间:2017-05-18 09:56:18

标签: c# linq

尝试这样做,不同的数据库:

var IDs =  (from a in db1.Table1 
            join b in db1.Table2 on a.Id equals b.Id 
            orderby a.Status 
            where b.Id == 1 && a.Status == "new" 
            select new Company { a.Id }).ToList();

var query = (from c in db2.Company
            join a in IDs on c.Id equals a.Id
            select new Company { Id = a.Id, CompanyId = c.CompanyId }).OrderByDescending(z => z.CompanyId).ToList();

我明白了:

Additional information: Unable to create a constant value of type 'M.Models.Company'. Only primitive types or enumeration types are supported in this context.

我认为这是因为第二次查询时的ToList()。

1 个答案:

答案 0 :(得分:0)

这里最有可能的问题是第二个查询没有很好的方法将表示为连接。我怀疑你最好的选择是切换到Contains

var IDs =  (from a in db1.Table1 
            join b in db1.Table2 on a.Id equals b.Id 
            where b.Id == 1 && a.Status == "new" 
            select a.Id).Distinct().ToList();

var query = (from c in db2.Company
            where IDs.Contains(c.Id)
            select new { Id = a.Id, CompanyId = c.CompanyId }
         ).OrderByDescending(z => z.CompanyId).ToList();

这不太理想,它会为大型列表而烦恼,但它至少是一种更简单的模式来表示参数化查询。