简体   繁体   English

在Entity Framework 4中从父级获取子级

[英]Get child from parent in Entity Framework 4

I'm new to Entity Framework and for now I can load the parent by id. 我是Entity Framework的新手,现在可以按ID加载父对象。

But I want to access to the child property from my parent after I load the parent. 但是我想在加载父级后从父级访问child属性。

    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. 您可以通过让查询知道您还需要Address子对象来实现。 You can do this by using "eager loading." 您可以使用“紧急加载”来完成此操作。 This is done by the Include("NavigationPropertyName") 这是通过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. 为了Employe起作用,您必须在edm中包括EmployeAddresses之间的关系。

You can use Include in your linq query: 您可以在linq查询中使用Include:

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. 在这种情况下,可以在不处理DBContext db的情况下使用var address = employe.Address ,并且EF可以从数据库中获取它。

Update: You should #using System.Data.Entity; 更新:您应该#using System.Data.Entity;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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