LINQ 选择中的 C# 子查询
Posted
技术标签:
【中文标题】LINQ 选择中的 C# 子查询【英文标题】:C# subquery in LINQ select 【发布时间】:2021-12-07 17:18:23 【问题描述】:我正在尝试将此查询转换为 LINQ,但我没有得到子查询的值
查询:
select c.cod, c.cpfcnpj, c.razaosocial, c.nome, c.fone, c.celular, c.email, c.dtcad, s.dataval as validade,
(select max(datapagamento) from vendas where c.cod = coduser) as datapag
from usuarios c, libsys s
WHERE c.cod = s.codcli
and c.cod in (select coduser from vendas)
AND c.cod in (select l.codcli from libsys l where l.dataval >= current_date)
order by c.dtcad asc
LINQ:
var rel = await (from u in _contexto.usuarios
from v in _contexto.libsys
where (
(u.cod == v.codcli) &&
_contexto.vendas.Any(y => y.coduser == u.cod) &&
_contexto.libsys.Any(y => y.codcli == u.cod && y.pcpdataval >= System.DateTime.Now)
)
select new RelatorioLicsModel
cod = u.cod,
cpfcnpj = u.cpfcnpj,
razaosocial = u.razaosocial,
nome = u.nome,
fone = u.fone,
celular = u.celular,
email = u.email,
dtcad = u.dtcad,
validade = v.pcpdataval.ToString(),
dtpag = Convert.ToDateTime(_contexto.vendas.Where(s => s.datapagamento == _contexto.vendas.Max(x => x.datapagamento) && s.coduser == u.cod).FirstOrDefault())
).ToListAsync();
我得到的错误是:
“您的 SQL 语法有错误;请查看与您的 mysql 服务器版本相对应的手册,了解在 '(PARTITION BY v
.coduser
ORDER BY v
附近使用的正确语法.cod
) AS row
\r\n FROM vendas
' 在第 7 行"
这是正确的方法吗?感谢您的帮助!
【问题讨论】:
【参考方案1】:dtpag
属性存在问题。
var query =
from u in _contexto.usuarios
from v in _contexto.libsys
where (
(u.cod == v.codcli) &&
_contexto.vendas.Any(y => y.coduser == u.cod) &&
_contexto.libsys.Any(y => y.codcli == u.cod && y.pcpdataval >= System.DateTime.Now)
)
select new RelatorioLicsModel
cod = u.cod,
cpfcnpj = u.cpfcnpj,
razaosocial = u.razaosocial,
nome = u.nome,
fone = u.fone,
celular = u.celular,
email = u.email,
dtcad = u.dtcad,
validade = v.pcpdataval.ToString(),
dtpag = Convert.ToDateTime(_contexto.vendas.Where(s => s.coduser == u.cod).Max(x => x.datapagamento))
【讨论】:
以上是关于LINQ 选择中的 C# 子查询的主要内容,如果未能解决你的问题,请参考以下文章
为啥 LINQ-to-Entities 将此查询放在子选择中?