如何为实体框架将此SQL查询转换为LINQ

时间:2019-04-11 13:48:55

标签: c# sql asp.net entity-framework linq

我是LINQ的新手,现在尝试学习查询的基础知识,由于实体框架,我需要将此SQL转换为LINQ。

SELECT Desktop, Notebook,Gmail, Telefone, Smartphone, Rede, Outros 
FROM Atributos, Gestors, Funcionario, CentroCusto 
WHERE Funcionario.Id = Atributos.Funcionario_Id 
AND Funcionario.CentroCusto_Id = CentroCusto.Id 
AND CentroCusto.Gestor_Id = Gestors.Id 
AND Gestors.Email = 'john@email.com'

2 个答案:

答案 0 :(得分:3)

这里的另一个问题中有一个非常详细的解释:How to do a join in linq to sql with method syntax?

但是,我认为这是您要寻找的:

from g in Gestors
    join f in Funcionario on g.Id equals f.Gestor_Id 
    join a in Atributos on f.Id equals a.Funcionario_Id
    join c in CentroCusto on f.CentroCusto_Id equals c.Id
where g.Email == "john@email.com"
select new 
{
    //your fields with their tables prefixes
}

对于联接,我喜欢使用这种语法,因为对于刚开始使用Linq的人来说,它更易于阅读和从SQL转换。您可以使用Lambda语法,但是如果您刚入门,那么在您对Lambda进行更多练习之前,这将是最容易掌握的。 另外,由于我不知道上面的查询中的表结构是什么样(索引,fk,pk),因此可以显着提高性能。

答案 1 :(得分:2)

实体创建映射到您的数据库的类。因此,下面是这些类和查询以获取数据的示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication108
{
    class Program
    {

        static void Main(string[] args)
        {
            string email = "john@email.com";
            DataBase db = new DataBase();
            var results = (from atr in db.Atributos
                           join fun in db.Funcionario on atr.Funcionario_Id equals fun.Id
                           join cen in db.CentroCusto on fun.CentroCusto_Id equals cen.Id
                           join ges in db.Gestors on cen.Gestor_Id equals ges.Id
                           where ges.Email == email
                           select new { desktop = atr.Desktop, notebook = atr.Notebook, gmail = atr.Gmail, tele = atr.Telefone, smartPhone = atr.Smartphone, rede = atr.Rede, outros = atr.Outros })
                           .ToList();
        }

    }
    public class DataBase
    {
        public List<Atributos> Atributos { get; set; }
        public List<Gestors> Gestors { get; set; }
        public List<Funcionario> Funcionario { get; set; }
        public List<CentroCusto> CentroCusto { get; set; }
    }
    public class Atributos
    {
        public string Funcionario_Id { get; set; }

        public string Desktop { get; set; }
        public string Notebook { get; set; }
        public string Gmail { get; set; }
        public string Telefone { get; set; }
        public string Smartphone { get; set; }
        public string Rede { get; set; }
        public string Outros { get; set; }
     }
    public class Gestors
    {
        public string Id { get; set; }
        public string Email { get; set; }
    }
    public class Funcionario
    {
        public string Id { get; set; }
        public string CentroCusto_Id { get; set; }
    }
    public class CentroCusto
    {
        public string Id { get; set; }
        public string Gestor_Id { get; set; }
    }






}