7 votes

How to project only some properties of a LINQ query?

Hello I am working with Entity Framework Code First, the environment is desktop(Windows Forms) and my query is the following.

I need to load a DataGridView with only two properties, id and description, can you make this select using linq?

The idea is to load only these two properties of the entity, not to bring me across the entire entity. how can I do using linq using IEnumerable to bring a list?

public IEnumerable<Proveedor> GetProveedor()
{
    //TO DO....
}

It is just a query that I offer Leandro is already solved, just that I wanted to avoid creating a class ProveedorExtend where to put my properties ProveedorId, RazonSocial With this would solve that I don't bring the rest of the columns to the DGV

5voto

Leandro Tuttini Points 25288

>>I need to load a DataGridView with only two properties id and description, you can make this select with linq?

could you define these fields in the select linq

List<xxClass> result = (from item in db.Entidad
                       select new xxClass(){
                           id = item.Id,
                           descripcion = item.descripcion
                       }).ToList();

of course defines the class with these two properties

public class xxClass{
      public int Id {get;set;}
      public string descripcion {get;set;}
}

the List<> implements IEnumerable<>

>>isn't it necessary to make a class to extend with these two properties? it is but that is what I want to avoid.

could you implement inheritance between classes

public class xxClassBase{
      public int Id {get;set;}
      public string descripcion {get;set;}
}

public class xxClass : xxClassBase {
      public int Prop1{get;set;}
      public string Prop2{get;set;}
}

In EF, you map the entire entity, but when you do the linq only do you get the two that are of utility

Also you could implement

[Entity Framework][Code First] Split Table (Table Splitting)

with this you can separate the table into entities by differentiating between the properties.

2voto

If possible. You can do something like the following, bearing in mind that in this example I assume that you will connect to the data directly from the presentation layer (that is from your form).

This is the class from which you want to obtain the data

 public class Persona
{ 
   public int Id { get; set; } 
   public string Nombre { get; set; } 
   public int Edad { get; set; } 
   public string Direccion { get; set; } 
} 
 

And with Linq you can do the following

  using (var db = new PersonaContext()) 
 {
    var query = (from p in db.Persona select new {p.Id, p.Nombre}).ToList();
    dataGridView1.DataSource = query;
 } 
 

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X