Calculated field with RU

Asked

Viewed 102 times

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 consult with EF to pick up the amount of vehicles for each customer. In a single query.

1 answer

6


Supposing Clientes be the DbSet of Cliente and db be the data context

Sum all customer vehicles 1

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

Or

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

Or with customer data together

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.