如何将SQL
转换为LINQ
?基本上,我有一个project_mstr
表,其中包含PR_CLASS
,PR_TYP
和PR_GRP
列。这3列是params_mstr
下param_cd
下的值。例如,记录的PR_TYP
值为param_cd
,Regular
为param_val
值。
我安装了Linquer但我不习惯使用它,因为我仍然需要创建与数据库的连接。我也无法找到在线SQL
到LINQ
转换器。所以我要求这里的好人帮我转换。
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;
答案 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,
}