I have an DbContext and many entities. I want to cache one entity of them. I.e. I have an entity Address
:
public partial class Address : BaseEntity
{
public string Street { get; set; }
public string City { get; set; }
public string ZipPostalCode { get; set; }
public int StateProvinceId { get; set; }
public string ContactName { get; set; }
public string ContactPhone { get; set; }
public string ContactFaxNumber { get; set; }
public string ContactEmail { get; set; }
public virtual StateProvince StateProvince { get; set; }
}
and StateProvince
:
public partial class StateProvince : BaseEntity
{
public string Name { get; set; }
public string Abbreviation { get; set; }
public int TruckSpeedLimit { get; set; }
}
when I get address by Id, for example:
var address = _db.Addresses.Where(p=>p.Id == id).FirstOrDefault();
and then try to get State name:
var state = address.StateProvince.Name;
It creates one more request to DB. If I have a list of addresses, it creates count of list element additional requests
Of course, I can create DTO class and do projection in Linq query like:
var address = _db.Addresses.Where(p=>p.Id == id).Select(p=> new AddressDTO{ Id = p.Id, ..., StateName = p.StateProvince.Name..}).FirstOrDefault();
but my code architect does not like DTO classes at all and I also don't want to do duplicate classes for simple entities.
State list is static. How can I say to EF : "cache states, please!" and avoid to additional requests to db?