将SQL转换为lambda表达式

时间:2017-04-27 18:03:19

标签: asp.net linq asp.net-mvc-4 lambda

如何将其转换为lambda表达式?有人可以帮忙吗?

SELECT 
    p.*
FROM
    db.MainProduct p 
WHERE
    p.id IN (SELECT ms.MainProductId 
             FROM db.MainProductToSupplierProduct ms)
    AND (p.description LIKE '%' + @filter + '%' 
         OR Coalesce(@filter,'') = '')

2 个答案:

答案 0 :(得分:0)

以下代码可以帮助您

var filteredMainProduct= MainProduct.Where(t => MainProductToSupplierProduct.Any(z => z.MainProductId == t.id) && @filter != null ? t.description.Contains(@filter) : t.FareBasisDescription.Contains(""));

答案 1 :(得分:0)

或者在查询语法中:

var ans = from p in db.MainProduct where (from ms in db.MainProductToSupplierProduct select ms.MainProductId).Contains(p.id) && (filter == "" || p.description.Contains(filter)) select p;

不确定这是最有效的方式,不太直接的翻译会使用连接:

var ans = from p in db.MainProduct join ms in db.MainProductToSupplierProduct on p.id equals ms.MainProductId where filter == "" || p.description.Contains(filter) select p;

这是一个左半连接,实现它的最好方法可能是SQL中的EXISTS - 它可能比加入更快:

var ans = from p in db.MainProduct where db.MainProductToSupplierProduct.Any(ms => ms.MainProductId == p.id) && (filter == "" || p.description.Contains(filter)) select p;