我有一个这样创建的匿名对象集合:
var srcCategories = srcSet.Categories.Select(c => new
{
ApplicationId = c.IsGLobal ? (long?)null : c.App.Id,
c.Name
});
请注意,此集合并非来自我的数据上下文;它是从外部系统的输入生成的。我需要同时映射数据库 ApplicationId
中的实体和Name
实体。到目前为止,这是我能够成功使其工作的唯一方法:
var trgCategoryIds =
(from c in core.Domain.Categories.AsEnumerable()
let ci = new { c.ApplicationId, c.Name }
where srcCategories.Contains(ci)
select c.Id)
.ToArray();
但这需要我Categories
先将整个表拉入内存。我正在寻找一种更有效的方法来执行此操作,最好是在单个查询中。我已经尝试了以下所有选项,它们都不能转换为sql:
// Removed .AsEnumerable()
var trgCategoryIds =
(from c in core.Domain.Categories
let ci = new { c.ApplicationId, c.Name }
where srcCategories.Contains(ci)
select c.Id)
.ToArray();
// Use .Any() instead of .Contains()
var trgCategoryIds =
(from c in core.Domain.Categories
where srcCategories.Any(s => s.ApplicationId == c.ApplicationId && s.Name == s.Name)
select c.Id)
.ToArray();
// Use Tuples instead of anon types
var srcCategories = srcSet.Categories.Select(c => Tuple.Create(...));
var trgCategoryIds =
(from c in core.Domain.Categories
let ci = Tuple.Create(c.ApplicationId, c.Name)
where srcCategories.Contains(ci)
select c.Id)
.ToArray();