Field calculated with EF

2

I have two classes:

 public class Cliente 
 {
      public int Id {get;set;
      public string Nome { get; set; }
      public string Email { get; set; }
      public string Telefone { get; set; }
      public string Celular { get; set; }
      public virtual ICollection<Veiculo> Veiculos { get; set; }
 }

 public class Veiculo
 {
    public string Marca { get; set; }
    public string Modelo { get; set; }
    public int Ano { get; private set; }
    public string Placa { get; set; }
 }

I would like to make an inquiry with EF to get the number of vehicles for each customer. In a single query.

    
asked by anonymous 29.11.2016 / 19:24

1 answer

6

Assuming that Clientes is DbSet of Cliente and db is the data context

Add all vehicles from customer 1

var qtdVeiculos = db.Clientes.Find(1).Veiculos.Count();

Or

var qtdVeiculos = db.Veiculos.Count(v => v.IdCliente == 1);

Or with the client data together

Obviously it will only work if the ClienteId property exists in the Veiculo

var model = db.Clientes.Select(c => new
                              {
                                  c.Nome,
                                  QtdVeiculos = c.Veiculos.Count()
                              });
    
29.11.2016 / 19:28