FrankSharp
FrankSharp

Reputation: 2632

Get child from parent in Entity Framework 4

I'm new to Entity Framework and for now I can load the parent by id.

But I want to access to the child property from my parent after I load the parent.

    protected void getChild_Click(object sender, EventArgs e)
    {
        JeansEntities db = new JeansEntities();
        Employe employe = db.Employes.SingleOrDefault(p => p.Id == 3);

        uxCountry.Text = //(address.Country) Its the child of Employe, but I can acces by the parent
    }

enter image description here

Thanks

Upvotes: 0

Views: 1554

Answers (2)

Kirill Bestemyanov
Kirill Bestemyanov

Reputation: 11964

You can use Include in your linq query:

Employe employe = db.Employes.Include(e=>e.Address).SingleOrDefault(p => p.Id == 3);

Or you can use lazy evaluation if your navigation property is virtual. In this case you can use var address = employe.Address when your DBContext db is not disposed, and EF get it from database for you.

Update: You should #using System.Data.Entity;

Upvotes: 0

Khan
Khan

Reputation: 18142

You can achieve this by letting the query know that you also want the Address child. You can do this by using "eager loading." This is done by the Include("NavigationPropertyName")

protected void getChild_Click(object sender, EventArgs e)
{
    JeansEntities db = new JeansEntities();
    Employe employe = db.Employes.Include("Addresses")
       .SingleOrDefault(p => p.Id == 3);

    var address = employe.Addresses.FirstOrDefault();

    if (address != null)
        uxCountry.Text = address.Country;
}

In order for this to work you must include a relationship between Employe and Addresses in the edm.

Upvotes: 1

Related Questions