asp.net IQueryable的SQL到LINQ转换

时间:2013-09-27 13:00:11

标签: sql asp.net-mvc linq sql-to-linq-conversion

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

2 个答案:

答案 0 :(得分: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来修改列表。

答案 1 :(得分: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();