我是C#的新手,我有一个别人设计的数据库,查询效果很好,但与SQL相比,速度慢了10倍。
我肯定在这里犯了错误,任何人都有提示加快这一点。此模型用于在表格中显示,我将int
转换为ENUM
并计算显示的折扣。
代码是:
var results = from w in db.Washes.AsEnumerable()
join t in db.Wash_Types.AsEnumerable() on w.WashTypeId equals t.Id
join a in db.Accounts.AsEnumerable() on w.AccountId equals a.Id
orderby w.Id descending
select new AllWashesTable
{
Id = w.Id,
WashTime = w.WashTime,
WashTimeEnd = w.WashTimeEnd,
Name = a.Name,
Client = (w.Client != null ? w.Client.Naziv : ""),
MobileNumber = a.MobileNumber,
Identification = w.Identification,
WashType = WashTypeShowEnum.WashTypeShowEnumToString((WashTypeShowEnum.WashType) w.WashTypeId),
Price = int.Parse(t.WashPrice) * (1 - w.Discount) + "",
Discount = w.Discount
};
return results.ToList();
似乎我所有的实体查询都比SQL慢至少5倍。某处我犯了一些错误。
答案 0 :(得分:2)
您的问题是使用AsEnumerable
。当执行查询时(在您的情况下为results.ToList()
),将使用linq-to-objects评估其后出现的所有内容。这意味着DB不会处理您的连接。您将从表中获取所有记录。
但是,实体框架无法识别您的函数WashTypeShowEnum.WashTypeShowEnumToString
。
您可能希望将AsEnumerable
移至结尾,然后select
结果。
var results = (from w in db.Washes
join t in db.Wash_Types on w.WashTypeId equals t.Id
join a in db.Accounts on w.AccountId equals a.Id
orderby w.Id descending
select new {w, a, t}).AsEnumerable().Select(arg=> new AllWashesTable
{
Id = arg.w.Id,
WashTime = arg.w.WashTime,
WashTimeEnd = arg.w.WashTimeEnd,
Name = arg.a.Name,
Client = (arg.w.Client != null ? arg.w.Client.Naziv : ""),
MobileNumber = arg.a.MobileNumber,
Identification = arg.w.Identification,
WashType = WashTypeShowEnum.WashTypeShowEnumToString((WashTypeShowEnum.WashType) arg.w.WashTypeId),
Price = int.Parse(arg.t.WashPrice) * (1 - arg.w.Discount) + "",
Discount = arg.w.Discount
};
return results.ToList();