我有这个LINQ:
private static object getObjectModels(DbContext context, IQueryable<int> contractsID)
{
return (from objectModel in context.Set<ObjectModel>()
where "column named conId contains contractsID "
select new ContractHelper
{
Id = contract.Id,
ClientId = contract.ClientId,
});
}
我需要从表记录中选择名为conID的列具有contractID值的值。
contractsID是int数组。 conID是int value列。
我在这一行写了什么: “名为conId的列包含contractsID” 获取列conID的项目等于contractID数组中的项目的所有记录?
答案 0 :(得分:4)
您可以将where子句反转并使用&#39; contains&#39;,例如:
private static object getObjectModels(DbContext context, IQueryable<int> contractsID)
{
return (from objectModel in context.Set<ObjectModel>()
where objectModel.conId.HasValue && contractsID.Contains(objectModel.conId)
select new ContractHelper
{
Id = contract.Id,
ClientId = contract.ClientId,
});
}
您可能需要将IQueryable转换为列表。
var myIds = contractIDs.ToList();
...
where myIds.Contains(objectModel.conId)
...
答案 1 :(得分:2)
您可以使用int数组使linq转换为正确的IN SQL语法
private static object getObjectModels(DbContext context, IQueryable<int> contractsID)
{
// Necessary to translate Contains to SQL IN CLAUSE
int [] contractIdsArray = contractsID.ToArray() ;
return (from objectModel in context.Set<ObjectModel>()
where contractIdsArray.Contains(objectModel.conId)
select new ContractHelper
{
Id = contract.Id,
ClientId = contract.ClientId,
});
}