填充复合类的最有效方法

时间:2014-03-20 23:19:08

标签: c# performance entity-framework entity-framework-4

我只想对使用EF4.0填充复合类的最有效,最快捷的方法有所了解。我有一个父类,其结构类似于下面的类。它反映了我的数据库结构。

public class Person
{
   public string FirstName { get; set; }
   ........
   public Address WorkAddress { get; set; }
   public IList<Account> Workspace { get; set; }
}

public class Address
{
   public string FirstName { get; set; }
   ......
}

public class Account
{
   public string SortCode { get; set; }
   public IList<string> TransactionHistory {get; set;}
   ......
}    

所以,在这个时刻,我把所有的人员拉回来了。从EF和我循环遍历每个,并填写每个地址和帐户。延迟加载已启用,因此我必须将所有循环封装在using语句中,否则当我尝试通过它们进行迭代时,我的帐户将为空。那么,我是否可以仅为此呼叫禁用延迟加载,或者以其他方式接近我的人员列表。

using (var entities = new PersonEntities())
{
    var dbPeople = (from person in entities.Persons
                    select person).ToList();

    foreach(var person in dbPeople)
    {
        foreach(var account in person.Accounts)
        {
           // In here I populate my 'Person' business object account and add it to my collection to return.
        }  
    }
}

1 个答案:

答案 0 :(得分:0)

如果我说得对,那么您将包含保持LazyLoading启用的关系。您可以使用Include方法为查询执行此操作:

using (var entities = new PersonEntities())
{
    var dbPeople = entities.Persons.Include("Accounts").ToList();

    foreach(var person in dbPeople)
    {
        //Do nothing with Accounts if the relation is mapped correct
    }
}

编辑: 您还可以为创建的PersonEntities实例的生命周期禁用LazyLoading:

using (var entities = new PersonEntities())
{
        entities.Configuration.LazyLoadingEnabled = false;
        //...
}