将具有同一表的多个连接(具有多个条件)的SQL转换为LINQ

时间:2016-09-27 02:18:08

标签: c# sql linq

如何将SQL转换为LINQ?基本上,我有一个project_mstr表,其中包含PR_CLASSPR_TYPPR_GRP列。这3列是params_mstrparam_cd下的值。例如,记录的PR_TYP值为param_cdRegularparam_val值。

我安装了Linquer但我不习惯使用它,因为我仍然需要创建与数据库的连接。我也无法找到在线SQLLINQ转换器。所以我要求这里的好人帮我转换。

SELECT 
    c.pr_id, c.pr_class, c.pr_typ, c.pr_grp, cp.pr_price, 
    c.gl_acct_id, c.pr_DESC "Project", 
    pm.param_val "Project Class", pm2.param_val "Project Type", pm3.param_val "Project Group"
FROM project_mstr c
JOIN 
    params_mstr pm ON c.pr_class = pm.param_id AND pm.param_cd = 'PR_CLASS'
JOIN 
    params_mstr pm2 ON c.pr_typ = pm2.param_id AND pm2.param_cd = 'PR_TYP'
JOIN 
    params_mstr pm3 ON c.pr_grp = pm3.param_id AND pm3.param_cd = 'PR_GRP'
JOIN 
    pr_price_mstr cp ON c.pr_id = cp.pr_id
JOIN 
    gl_acct_mstr gl ON c.gl_acct_id = gl.gl_acct_id
ORDER BY 
    c.crea_dt DESC;

1 个答案:

答案 0 :(得分:3)

LINQ-to-SQL仅支持equijoins,因此如果需要在连接中引入多个值,可以创建一个匿名类来表示所有要连接的值(请注意,匿名类必须相同) type,这意味着他们需要(1)具有完全相同类型的完全相同类型(3)的字段(2)的完全相同的名称。)

from c in ProjectMstr
join pm in ParamsMstr on new { ParamId = c.ChClass, ParamCd = "CH_CLASS" } equals new { pm.ParamId, pm.ParamCd }
join pm2 in ParamsMstr on new { ParamId = c.ChClass, ParamCd = "CH_TYP" } equals new { pm2.ParamId, pm2.ParamCd }
join pm3 in ParamsMstr on new { ParamId = c.ChClass, ParamCd = "CH_GRP" } equals new { pm3.ParamId, pm3.ParamCd }
// …
orderby c.CreaDt descending
select new {
    c.ChId,
    // …
    ProjectClass = pm.ParamVal,
    ProjectType = pm2.ParamVal,
    ProjectGroup = pm3.ParamVal,
}

或者,如果它没有更改查询的逻辑,您可以将连接中的常量值拉出到where

from c in ProjectMstr
join pm in ParamsMstr on c.ChClass equals pm.ParamId
join pm2 in ParamsMstr on c.ChClass equals pm2.ParamId
join pm3 in ParamsMstr on c.ChClass equals pm3.ParamId
// …
where pm.ParamCd == "CH_CLASS"
where pm2.ParamCd == "CH_TYP"
where pm3.ParamCd == "CH_GRP"
orderby c.CreaDt descending
select new {
    c.ChId,
    // …
    ProjectClass = pm.ParamVal,
    ProjectType = pm2.ParamVal,
    ProjectGroup = pm3.ParamVal,
}