我尝试使用Lambda表达式进行复杂查询(而不是我)。我有我想要的SQL"翻译"致Lambda。
SELECT MAX((SUBSTRING(tbp.dt,4,4)+SUBSTRING(tbp.dt,2,2)+SUBSTRING(tbp.dt,1,2))) as Dt,
tb._n, tbp.number, tbp.dsc
FROM TB_A tb
JOIN TB_B_C tbp ON tbp.number = tb.number
WHERE tbp.rec = 0 AND tbp.processing = 0 AND tb._n != '' AND tbp.error = 0
GROUP BY tb._n, tbp.number, tbp.dsc
到目前为止,我有这个Lambda Expression:
var results = db.a
.Join(db.b_c, proc => proc.number, andam => andam.number, (proc, andam) => new { proc, andam })
.Where(d => d.proc._n != "" && d.andam.rec == false && d.andam.processing == false && d.andam.error)
.ToList();
如何完成我的选择以获得与SQL查询相同的结果?如果可能的话,你可以解释一下如何正确思考"翻译"对Lambda的查询?
非常感谢。
答案 0 :(得分:1)
使用查询语法
通常更容易编写var results = from tb in db.a
join tbp in db.b_c on tb.number equals tbp.number
where tbp.rec == 0
&& tbp.processing == 0
&& tb._n != string.Empty
&& tbp.error == 0
group new {tb, tbp} by new {tb._n, tbp.number, tbp.dsc} into grp
select new
{
grp.Key._n,
grp.Key.number,
grp.Key.dsc,
Dt = grp.Max(x => x.tbp.dt.Substring(4,4)
+ x.tbp.dt.Substring(2,2)
+ x.tbp.dt.Substring(0,2))
};
答案 1 :(得分:0)
您需要做的就是
1)添加GroupBy
和Select
语句
或
2)将Join
替换为GroupJoin
。
以下示例与您的数据库架构无关...
选项1)
var results = ...
.GroupBy(x=> new {x.Field1, x.Field2, x.Field3})
.Select(grp=>new
{
Key = grp.Key,
MaxVal = grp.Max(o=>o.Field1)
});
选项2)
var result = db_a.Where(x=>x.Field1==1 && x.Field2==0)
.GroupJoin(db_b.Where(x=>x.Field3==5),
a => a.PrimaryKey,
b => b.ForeignKey,
(a, b) => new
{
PK=a.PrimaryKey,
MaxVal=b.Max(o=>o.Field2)
});
来源:https://msdn.microsoft.com/en-us/library/bb534297%28v=vs.110%29.aspx