SQL Syntax - LINQ in C #

2

I'm doing a small application where I need to save data in SQL Server and then view it in a Datagrid using WPF. I'm not used to LINQ but I've already done some tests but it's not very clear to me because there are two types of syntax ...

Example 1;

    var consulta = from x in bd.Tabla select x;

Example 2;

    var consulta = bd.Tabla.Where(x => x.Columna1 == "prueba");

Indeed, these are two different searches, but both are seen with either of the two syntax ... Which is more advisable to do?

And most importantly ... Is there a place where you can see a summary of the instructions INSERT, UPDATE, DELETE ... to be able to have it at hand?

What would the syntax of the following query look like if I want to do it using my own methods?

    var consulta = from x in bd.Tabla select x;
    
asked by Edulon 10.09.2017 в 09:37
source

3 answers

3

In the case of var consulta = from x in bd.Tabla select x; the equivalent in the methods syntax would be

var consulta = bd.Tabla.Select(x => x);

However the .Select(x => x) is most of the cases redundant since it returns the same elements without any modification for what you could do simply:

var consulta = bd.Tabla;

The only difference between the latter and the one above is the type of data it returns.

The first returns an IQueryable while the latter returns the data type of bd.Table (in case of Entity Framework for example DbSet<T> )

The reason why these two syntax exist is simple.

When the C # team made C # 3.0 together with NET Framework 3.0 they added many new things to the language including: lambdas, type inference (var), extension methods and partial methods, with the aim of being able to implement LINQ and its Querys syntax. The primary objective was to convert the imperative style in which the queries, selections, projections and other operations of the relational algebra were made to a declarative style as close to SQL as possible. p>

So given a variable

IEnumerable<Personas> personas = ....;

A code similar to this

IEnumerable<PersonasResumen> mayoresDeEdad = new List<Persona>();
foreach(Persona p in personas)
{
    if(p.Edad >= 18)
    {
        mayoresDeEdad.Add(p);
    }
}

It became simply

var mayoresDeEdad = from p in personas
                    where p.Edad >= 18
                    select p;

The thing becomes even more complicated if we take into account operations like JOIN

The syntax of methods is only the penultimate step to get to that syntax and sometimes it is preferred because in some cases it is shorter for example in the case that it is not required to make a projection (select only certain fields) the above may have been written in this way.

var mayoresDeEdad = personas.Where(p => p.Edad >= 18);

The select is not necessary in this case, in the query syntax it is mandatory.

For me the best explanation of LINQ is in this prehistoric interview of 2005 by the same teacher Anders Hejlsberg, creator of C #, LINQ and TypeScript. The video lasts 37 minutes, has low quality and is filmed with a camera pointing to the screen but the content and explanation are pure gold.

Anders Hejlsberg LINQ Demo 2005

Or if you want a better quality and you have a little more time this other video of the Lang.NET 2006 Compiler Symposium is also an excellent alternative

Anders Hejlsberg LINQ

Finally I just remind you that Insert, Update or Delete are not part of LINQ since as its name implies: Language Integrated Query is just a query language, not operations with side effects about the data.

It also works on any IEnumerable<T> not only on databases, so the way to do INSERT , UPDATE or DELETE depends on the provider that is being used, for example in the Entity Framework:

INSERT

db.Personas.Add(persona);
db.SaveChanges();

UPDATE

persona.Nombre = nuevoNombre;
db.SaveChanges();

DELETE

db.Personas.Remove(persona);
db.SaveChanges();
    
answered by 10.09.2017 / 18:53
source
1

The only notable difference between the two is readability, some people find it easier to use / understand linq declarative syntax
from x in bd.Table where (x = & x; x.Column1 == "test") select x;

while for others it is more natural to use linq syntax by methods var query = bd.Tabla.Where (x => x.Column1 == "test");

Here I leave the references link

    
answered by 10.09.2017 в 14:38
-1

I use the following syntax

var query = (from a in informacionDB.departamentos
                    join b in informacionDB.empleados on a.ID_Empleado_Jefe equals b.id_Empleado into b2
                    from b in b2.DefaultIfEmpty()
                    join c in informacionDB.departamentos on a.ID_DepartamentoArea equals (int)c.ID_Departamento into c2
                    from c in c2.DefaultIfEmpty()
                    orderby a.Descripcion
                    select new
                    {
                        a.ID_Departamento,
                        a.Descripcion,
                        a.Abreviatura,
                        a.Area,
                        b.Nombre,
                        Departamento = c.Descripcion
                    }).ToList();
        var query2 = (from d in query
                      select new gridDepartamentos
                      {
                          ID_Departamento = d.ID_Departamento,
                          Descripcion = d.Descripcion,
                          Abreviatura = d.Abreviatura,
                          Area = d.Area,
                          Nombre = d.Nombre,
                          Departamento = d.Departamento

                      }).ToList(); 

This is an Example of a LeftJoin query is a List and query2 is a list of a custom class gridDepartamentos

The following is an example of an insert:

 var primerInsert = new huellas()
        {

            codigo = codigo,
            ID_Empresa = idEmpresa,
            finger_data = Data,
            NumeroDedo = numeroDedo
        };
        informacionDB.huellas.Add(primerInsert);

        informacionDB.SaveChanges();

Example for Update:

var queryTest = (from a in informacionDB.empleados
                         where a.Codigo == 10
                         select a).FirstOrDefault();
        queryTest.Nombre = "CambiodeNombre";
        informacionDB.SaveChanges();
    
answered by 19.10.2017 в 23:52