如何将流动的sql查询转换为linq,以便我可以在我的Web api控制器中使用。
select * from String where StringNumber in
(
select Str1 from Detail where DetailNr = 6
union
select Str2 from Detail where DetailNr = 6
union
select Str3 from Detail where DetailNr = 6
union
select Str4 from Detail where DetailNr = 6
)
我尝试选择单个字符串数字,我想出了这个:
var str1 = _dataContext.Context.Detail.AsQueryable()
.Where(n => n.DetailNr == 6)
.Select(n => n.Str1 );
var str2 = _dataContext.Context.Detail.AsQueryable()
.Where(n => n.DetailNr == 6)
.Select(n => n.Str2 );
var str3 = _dataContext.Context.Detail.AsQueryable()
.Where(n => n.DetailNr == 6)
.Select(n => n.Str3 );
var str4 = _dataContext.Context.Detail.AsQueryable()
.Where(n => n.DetailNr == 6)
.Select(n => n.Str4 );
然后像这样:
var result= _dataContext.Context.String.AsQueryable()
.Where(s => s.StringNumber == str1 or str2 or str2 or str4).ToList();
这应该如何在 asp.net MVC 控制器中编写?也许使用 SelectMany 子句?
这将适用于 Linq to Objects,但 Linq to Entities 可能不支持:
var strings = _dataContext.Context.Detail.AsQueryable()
.Where(n => n.DetailNr == 6)
.Select(n => new [] {n.Str1, n.Str2, n.Str3, n.Str4});
.SelectMany(s => s);
var result= _dataContext.Context.String.AsQueryable()
.Where(s => strings.Contains(s)).ToList();
您可能需要添加 as AsEnumerable
才能使列表更加清晰。
var results = _dataContext.Context.Detail.Where (n => n.DetailNr == 6).ToList();
var concattedResults = results.Select(n => n.Str1)
.Concat(results.Select(n => n.Str2))
.Concat(results.Select(n => n.Str3))
.Concat(results.Select(n => n.Str4)).ToList();