简体   繁体   中英

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
    }

在此处输入图片说明

Thanks

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM