-1

I have two classes that partake in a parent-child relationship. The parent class is Country, and the child class is City:

public partial class Country
{
    public Country()
    {
        this.Cities = new List<City>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string AlphaCodeTwo { get; set; }
    public string AlphaCodeThree { get; set; }
    public Nullable<int> NumericCode { get; set; }
    public string Capital { get; set; }
    public string Nationality { get; set; }
    public Nullable<decimal> CapitalArea { get; set; }
    public Nullable<decimal> CapitalPopulation { get; set; }
    public string Image { get; set; }
    public virtual List<City> Cities { get; set; }
}

public partial class City
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
    public Nullable<int> NumericCode { get; set; }
    public virtual Country Country { get; set; }
}

When I select a City object with the following LINQ query, the navigation property to the parent class is null:

private List<Country> _Country;
var City = _Country.SelectMany(c => c.Cities).OrderBy(ci => ci.Name).ToList();

I get all children, but no parent data.

Developerzzz
  • 1,041
  • 1
  • 11
  • 23

1 Answers1

1

If you're using Entity Framework, you can use .Include() to grab the navigation property data as you load the objects. Note that it tends to produce some pretty gnarly queries.

var city = (
    from c in db.Cities.Include(c => c.Country)
    where c.CountryId == CountryId
    orderby c.Name
    select c
).ToList();
robrich
  • 12,467
  • 5
  • 30
  • 57