Problem C # winforms LinQ

1

I am working CodeFirst and I have the following table in my DB and when I want to show it the query in a DataGridView brings all fields, but I want to show only 2, exactly the name and the price. What should I modify in the Linq query?

var products = db.Products.Include(p => p.Category).OrderBy(p => p.Category.Name).ThenBy(p => p.Name);

dgvProductos.DataSource = products.ToList();

This is the class

public class Product
{
    [Key]
    [Column(Order = 0)]
    public int ProductId { get; set; }

    [Column(Order = 1)]
    [Display(Name = "Categoría")]
    public int CategoryId { get; set; }

    [Column(Order = 2)]
    [Display(Name = "Producto")]
    public string Name { get; set; }

    [Column(Order = 3)]
    [DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
    [Display(Name = "Precio de alquiler")]
    public decimal RentalPrice { get; set; }

    [Column(Order = 4)]
    [Display(Name = "Comentarios")]
    public string Remarks { get; set; }       

    public virtual Category Category { get; set; }

}
    
asked by Mario Gonzalez 20.06.2018 в 18:30
source

1 answer

0

The query that you do with lambda syntax should be changed to Linq so that you only get the fields you want:

var products = from p in db.Products
               join c in db.Category on p.CategoryId equals c.CategoryId 
               orderby c.Name, p.Name
               select new {
                   p.Name, P.RentalPrice
               };

Given your query, I do not see it necessary to make the join to categories since you are not making use of these data, I propose that your query be as follows:

var products = from p in db.Products
               orderby p.Name ascending
               select new {
                   p.Name, P.RentalPrice
               };
    
answered by 20.06.2018 в 18:44