对Linq的SQL查询使用方法语法

时间:2017-09-18 11:13:46

标签: sql linq

任何人都可以将此sql查询转换为Linq方法语法:

select isnull(upl_data, pol_defaultdata),
  upl_userid, upl_countryid, 
  pol_sadmModuleid, pol_name, 
  pol_namelabel,pol_datatype 
from sadmpolicy
left join userpolicy on upl_policyid = pol_id
where pol_scope = 3

2 个答案:

答案 0 :(得分:0)

你可以这样做:

var results = from l in sadmpolicyList
              join r in userpolicyList.Where(up=>up.pol_scope =3).ToList() on l.upl_policyid equals r.pol_id into G
from t in G.DefaultIfEmpty()
select new
{
  polData = l.upl_data ?? r.pol_defaultdata,
  upl_userid = l.upl_userid, 
  ...
};

(但我不确定哪个列来自哪个表,因此您可能需要调整别名。)

答案 1 :(得分:-1)

除了上面的答案,你可以稍微分解一下,然后做一些事情:

private string prepareSQLCondition(List<paramofsomekind> parameterList, number returnVal) { 

string condition = "SELECT ISNULL (upl_data, pol_defaultdata)";

int count = 1;
// Traverse params
foreach (var param in parameterList)
{
    if (parameterList.Count == count)
    {
        condition += "," + param.value + ",";
    }
    else
    {
       condition += "," + param.value + ",";
    }

    count++;
}

return condition + "WHERE pol_scope =" + returnVal;
}

从这里你可以添加更多功能层,应用更多控制流,或许可以满足某些异常,直到你得到一个完全动态的解决方案。

然后您可以使用以下方法调用您的方法: prepareSQLCondition("param1, param2, param3...,3); params的字符串表示形式是<List>