I am using Entity Framework 4.1 – Code First. I store user’s addresses as follows:
Country -> District -> City -> -> Area -> Address
That only applies to addresses inside my country where I provide all the available Districts, Cities and Areas in the country so the user can choose from. And then he fills his address details which are stored in the Addresses table.
In order to make this clearer, take a look at the following:
public class Address
{
public int Id { get; set; }
public string Name { get; set; }
[MaxLength(500)]
public string Details { get; set; }
public bool IsDefaultAddress { get; set; }
public string CountryName { get; set; }
public Area Area { get; set; }
public virtual User User { get; set; }
}
public class Area
{
public int Id { get; set; }
public string GoogleName { get; set; }
public string FamiliarName { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
public virtual City City { get; set; }
public string GetName
{
get { return FamiliarName ?? GoogleName; }
}
}
public class City
{
public int Id { get; set; }
public string Name { get; set; }
public virtual District District { get; set; }
public virtual ICollection<Area> Areas { get; set; }
}
public class District
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<City> Cities { get; set; }
public virtual Country Country { get; set; }
}
public class Country
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<District> Districts { get; set; }
}
I noticed that whether I use the virtual keyword or not, nothing changes. Area is always null for some reason.
How can I retrieve an address and have all the other info (area, city, district and country) objects not be null?
If you know that you will need them simply use eager loading:
If lazy loading doesn’t work when you mark
Areavirtualthen something else is wrong.