数据库查询中较慢的部分之一是从获取的数据传输到本地计算机。
人们往往会传输更多的数据,然后再使用。你也倾向于这样做。例如,您的广告类可能有几个外键 User、Status、Type 等,而 User、Status、Type 有一个主键,其值与您传输的相同.此外,我怀疑您是否会显示所有这些外键。
您说要显示最新产品,您的查询返回十二个最新产品。如果您真的只想要最新的,请使用FirstOrDefault。
假设您想要最新的几件商品,OrderByDescending 和 Take 可以解决问题。
您将方法语法与查询语法混合在一起。使用 C# 编程语言在集合中思考的人经常使用方法语法。此外,方法语法允许一些查询语法没有的功能。查询语法是对 C# 的改编,适用于在 SQL 查询中思考更多的人。如果您坚持这两种语法中的一种,人们会更容易理解您的代码的作用,从而更容易测试、调试和维护。见Query syntax vs Method syntax
您的查询可能会执行您想要的操作,但通过上述改进,我会这样做:
var result = _context.Advertisements // from all Advertisements
.OrderByDescending(advertisement => advertisement.PostedOn)
// order them by descending PostedOn
.Select(advertisement => new // from every result element make a new item
{ // containing the following properties
// take only the Advertisement properties you plan to use
Id = advertisement.Id,
PostedOn = advertiesment.PostedOn,
...
// Only if you plan to use properties of SubCategory:
SubCategory = new
{
// again: take only the properties you plan to use:
Name = advertisement.SubCategory.Name,
Type = advertisement.SubCategpru.Type,
...
// one of the items you wont use is the foreign key to Advertisements
}
// If you want you can return your items in a different structure
// for instance, convert your City/Province/Country into an address:
Address = new
{
City = advertisment.City.Name,
Province = advertisement.City.Province.Name,
State = advertisement.City.Province.State.Name,
}
// etc for the other properties
})
// Select will keep the original oder
// take only the first twelve of them
.Take(12)
// only do the ToList() if you know this is the end result
.ToList();
我在 Select 之前订购,以便在查询后不再需要 PostedOn 时可以省略它。