【问题标题】:most efficient way to populate composite class填充复合类的最有效方法
【发布时间】:2014-03-20 23:19:08
【问题描述】:

我只是想就使用 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 语句中,否则当我尝试迭代它们时,我的 Accounts 将为空。那么,我可以只为此调用禁用延迟加载,还是应该以其他方式接近我的人员列表中的人口。

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.
        }  
    }
}

【问题讨论】:

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


    【解决方案1】:

    如果我没听错,您将包括保持启用 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;
            //...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2019-09-03
      • 2012-04-01
      • 2021-06-03
      • 2016-09-06
      • 2011-08-12
      相关资源
      最近更新 更多