c# - 如何将带有子查询的 SQL 查询转换为 .NET Core 查询

标签 c# mysql .net-core mariadb

我有下一个 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/

相关文章:

c# - 在 WP7 上将位图保存为 PNG

c# - Entity Framework 代码优先 : CASCADE DELETE for same table many-to-many relationship

c# - 通过 .NET 核心与 WMI 交互

c# - 为什么在使用 Microsoft.Bcl 时不能在我的 Windows Phone 7.1 MvvmCross 项目中使用 await 关键字 - 不能等待 'System.Threading.Tasks.Task?

c# - 每个 parent 只选择 1 个 child

php - 数据库之间的 Blob 编码差异

sql - 找到表有二进制数据

mysql - 为什么通过 MS Access 更新 MySQL 表比插入一行占用更多?

c# - 如何删除应用程序代码中的 app.config

c# - 如何在 Linux 上的 .NET 6 中写入文件描述符 3 而不是 stdout?