我有以下类(class):
public class CountryVM
{
#region Properties
public int CountryID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
#endregion
#region Constructors
/// <summary>
/// Constructor
/// </summary>
public CountryVM()
{
}
/// <summary>
/// Constructor that creates a View Model based of an Entity object
/// </summary>
/// <param name="countryCode">Fills data to View Model</param>
public CountryVM(Country_Code countryCode)
{
if (countryCode != null)
{
CountryID = countryCode.Country_Code_ID;
Code = countryCode.Country_Code1;
Name = countryCode.Country_Name;
}
}
#endregion
}
public class StateVM
{
#region Properties
public int StateID { get; set; }
public int CountryID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public CountryVM Country { get; set; }
#endregion
#region Constructors
/// <summary>
/// Constructor
/// </summary>
public StateVM()
{
}
/// <summary>
/// Constructor that creates a View Model based of an Entity object
/// </summary>
/// <param name="stateCode">Fills data to View Model</param>
public StateVM(State_Code stateCode)
{
if (stateCode != null)
{
StateID = stateCode.State_Code_ID;
CountryID = stateCode.Country_Code_ID;
Code = stateCode.State_Code1;
Name = stateCode.State_Name;
Country = new CountryVM(stateCode.Country_Code);
}
}
#endregion
}
Country_Code 和 State_Code 都是我的表中转换为实体对象的表。
我运行以下代码行:
IEnumerable<State_Code> entityList = _stateRepository.GetAllStateCodes();
IEnumerable<StateVM> viewModelList = entityList.Select(s => new StateVM(s));
viewModelList = viewModelList.ToList();
运行时
viewModelList = viewModelList.ToList();
需要 1 到 3 秒。我正在尝试它并删除了:
Country = new CountryVM(stateCode.Country_Code);
来自 StateVM 对象,它会完美运行。
所以,我猜之所以需要这么长时间,是因为一旦 StateVM 被实例化,内部就会实例化一个 CountryVM。
有什么办法可以提高性能吗?
最佳答案
运行 ToList() 将始终枚举集合。您遇到的是所有延迟加载的属性,这些属性链接到执行生成的 SQL 语句的其他表以获取附加的数据属性。如果您不需要它们,您应该过滤您的集合,直到您确定您拥有继续前进所需的最少量数据。如果您知道需要它们,则可以使用预先加载来加载原始请求中的所有内容,而不是在对象到对象到属性到属性的基础上加载。看看ObjectQuery.Include
关于c# - 转换具有多个对象的 IEnumerable 时,ToList() 花费很长时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37174936/