How can I query the DB to return a list of items that have fields in addition to what the entity models describe>
Say I have entity models called Owners and Pets:
public class Owner
{
public int OwnerID{ get; set; }
public virtual IEnumerable<Pets> Pets{ get; set; }
}
public class Pet
{
public int PetID{ get; set; }
public string PetName{ get; set; }
public int OwnerID{ get; set; }
public Owner Owner{ get; set; }
}
If I got a list of owners like this:
dbContext.Set<Owner>().ToList()
Each object in that list would be an Owner with OwnerID and a list of their pets.
But, what if I wanted to include an extra field for each of those Owners, like “HasPets”, and have a list of viewmodels that accepts that.
public class OwnerViewModel
{
public int OwnerID{ get; set; }
public bool HasPets{ get; set; }
}
List<OwnerViewModel> OwnerViewModels = ....(get list with added field)
I have no idea how to query the DB to include a new calculated field…
(I realize I could simply do a count on Owner.Pets, but I just wanted to keep the example simple)
Something like
And define your viewmodel like:
Or you can load all the pets client-side, and check them there (of course not recommended for the overload):