【问题标题】:Sql Query to Linq With method syntax带有方法语法的 Sql Query to Linq
【发布时间】:2017-09-18 11:13:45
【问题描述】:

任何人都可以将此 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

【问题讨论】:

  • 请参考 SO How To Ask - 您应该显示您尝试过的 linq 并解释问题出在哪里(为 null 或左连接或 wheres 等)

标签: sql linq


【解决方案1】:

你可以这样做:

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, 
  ...
};

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

【讨论】:

    【解决方案2】:

    在上面的答案的基础上,您可以将其分解一下并按照以下方式做一些事情:

    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);其中参数的字符串表示是你的&lt;List&gt;

    【讨论】:

    • 您的回答中哪一部分涉及 LINQ?其次,对于 SQL 注入,您的答案是成熟
    猜你喜欢
    • 2015-05-27
    • 1970-01-01
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多