实体LINQ Ienumerable异步

问题描述 投票:-2回答:1

我有查询,我需要总结所有日常工作。问题是 - 我需要它不要锁定UI并且是async,但Enumberable不支持Async。我使用Enumberable将日期String解析为DateTime对象。

任何相同结果的提示,但异步。

var pattern = "dd.MM.yyyy HH:mm:ss";
var result = (from w in db.Washes.AsEnumerable()
                group w by new {Date = DateTime.ParseExact(w.WashTime, pattern, null).Date}
                into g
                orderby g.Key.Date descending 
                select new DailyAverageModel {
                    Date = g.Key.Date,
                    NoOfWashesPerDate = g.Count()
                }).ToList();
c# entity-framework linq
1个回答
0
投票

您可以将其分为2个查询,1个用于检索哪个是异步,另一个用于创建结果。这样,瓶颈(数据存储检索)可以运行异步,这样您的UI就可以响应。

10个字符的子字符串基于DateTime字符串的格式,格式为"dd.MM.yyyy HH:mm:ss"(请参阅注释)。

var washes = await db.Washes
    .GroupBy(w => w.WashTime.Substring(0, 10))
    .Select(w => new {Date = w.Key, NoOfWashesPerDate = w.Count()})
    //.OrderByDescending(w => w.Date.Reverse()) // you could do this but the code would be more readable if this was omitted and done in memory
    .ToListAsync();

return washes.Select(w => new DailyAverageModel
{
    Date = DateTime.ParseExact(w.Date, pattern, null),
    NoOfWashesPerDate = w.NoOfWashesPerDate
}).OrderByDescending(w => w.Date).ToList();             

请注意,排序必须在内存中完成,因为对字符串进行排序会产生意外结果(除非您将其反转,然后在数据存储调用中排序)。

但真正的问题是数据存储架构将DateTime值存储为字符串。在设计数据存储时始终选择适当的类型。类型系统存在是有充分理由的。

注意 - EF支持Substring

© www.soinside.com 2019 - 2024. All rights reserved.