0

如何将流动的 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 子句?

4

2 回答 2

2

这适用于 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();

您可能需要添加AsEnumerable到 hyrdate 列表。

于 2013-09-27T13:07:30.653 回答
0
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();
于 2013-09-27T13:08:46.700 回答