我有下一个 SQL 原生查询:
select
a.id_agente,
a.alias,
a.direccion,
cd.description,
( select te.data
from tevento te
left join tagente ta on ta.id_agente = te.id_agente
where ta.id_agente = a.id_agente order by timestamp desc limit 1
) as data
from tagente a
left join tagent_custom_data cd on a.id_agente = cd.id_agent
where cd.id_field = 6 and cd.description = $VAR;
我在 Controller 的 .net 核心中有这样的查询:
[HttpGet]
public ActionResult<string> GetAgentesByPlanta(string idPlanta)
{
using (var db = new MyContext())
{
List<Object> lst = new List<Object>();
var q =
from a in db.Agente
join cd in db.CustomData on a.id_agente equals cd.id_agent
where ((cd.id_field == 6) & (cd.description == idPlanta))
select new { Agente = a, CustomData = cd };
foreach (var x in q)
{
lst.Add(new {
id_agente=x.Agente.id_agente,
nombre=x.Agente.nombre,
direccion=x.Agente.direccion,
alias=x.Agente.alias,
ultimo_contacto=x.Agente.ultimo_contacto
});
}
dynamic response = lst;
return Ok(response);
}
}
此 Controller 以 json 响应,并且可以正常工作。但是可以看到,select的子查询少了。
¿如何在此 .NET Core 查询中添加子查询?
最佳答案
你可以在这里使用 Eager Loading 修改@baquilare answer 作为示例
var q = from a in db.Agente
join cd in db.CustomData on a.id_agente equals cd.id_agent
join te in db.Evento.AsQueryable().Include(x=>x.Agente) on
te.Agente.id_agente == a.id_agente
where ((cd.id_field == 6) && (cd.description == idConvert))
select new {
Agente = a,
CustomData = cd,
Evento =te.OrderByDescending(x=>x.timestamp).FirstOrDefault()
};
Here again i dont know timestamp is in which table + it is more optimised then current code but can be improved a lot ... a simple advice using ef or efcore i will always advice to use a repository pattern you might be needing system.Linq namespace too
如果对 efcore 不严格,你也可以使用 sp 并通过 efcore 执行它,这对于像这样的查询更好
关于c# - 如何将带有子查询的 SQL 查询转换为 .NET Core 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58483103/