C# EF查询简化 var过滤器=新列表(); var collections=\u collectionManager.GetAll(); var storesLookup=collections.Select(c=>newlookupmodel { Id=c.StoreId, DisplayName=c.StoreName }).ToList(); var distinctstoresLookup=storesLookup.GroupBy(c=>new{c.DisplayName,c.Id})。选择(c=>c.First()).ToList(); 添加(新集合FilterModel(FilterVariables.Store) { FilterType=FilterDataType.Collection, AllowedValues=distinctstoresLookup });
有没有一种方法可以简化此查询或组合其中的一些查询?您可以删除中间C# EF查询简化 var过滤器=新列表(); var collections=\u collectionManager.GetAll(); var storesLookup=collections.Select(c=>newlookupmodel { Id=c.StoreId, DisplayName=c.StoreName }).ToList(); var distinctstoresLookup=storesLookup.GroupBy(c=>new{c.DisplayName,c.Id})。选择(c=>c.First()).ToList(); 添加(新集合FilterModel(FilterVariables.Store) { FilterType=FilterDataType.Collection, AllowedValues=distinctstoresLookup });,c#,performance,entity-framework,linq,C#,Performance,Entity Framework,Linq,有没有一种方法可以简化此查询或组合其中的一些查询?您可以删除中间ToList调用。它们不必要地将查询具体化为一个列表。看起来您的存储库应该查询数据库ToList强制客户端评估,这大大破坏了性能。使用SQL Server Profiler了解我的意思 很可能,\u collectionManager.GetAll()必须返回一个IQueryable 您的GroupBy只实现了一个Distinct。然后,从每组中选出第一个。但同一组中的所有对象都是相同的。我怀疑这是一个逻辑错误 根据查询结果,您可以
ToList
调用。它们不必要地将查询具体化为一个列表。看起来您的存储库应该查询数据库ToList
强制客户端评估,这大大破坏了性能。使用SQL Server Profiler了解我的意思
很可能,\u collectionManager.GetAll()
必须返回一个IQueryable
您的GroupBy
只实现了一个Distinct
。然后,从每组中选出第一个。但同一组中的所有对象都是相同的。我怀疑这是一个逻辑错误
根据查询结果,您可以将其转换为:
var filters = new List<AllowedFilterModel>();
var collections = _collectionManager.GetAll();
var storesLookup = collections.Select(c => new LookupModel
{
Id = c.StoreId,
DisplayName = c.StoreName
}).ToList();
var distinctstoresLookup = storesLookup.GroupBy(c => new {c.DisplayName,c.Id }).Select(c=>c.First()).ToList();
filters.Add(new CollectionFilterModel(FilterVariables.Store)
{
FilterType = FilterDataType.Collection,
AllowedValues = distinctstoresLookup
});
这比使用所有这些临时变量更具可读性。您想实现什么?目前的问题是什么?
GetAll()
是否返回尚未枚举的IQueryable
。。。你需要实际描述问题和目标,一个相当于“请解决这个”的问题是不被接受的。
var results =
_collectionManager.GetAll()
.Select(c => new LookupModel
{
Id = c.StoreId,
DisplayName = c.StoreName
})
.Distinct()
.ToList();