这是查询工作正常且不会导致问题的工作示例。为了简单起见,我跳过了数据库,直接进入了内存中的对象,这可能就是它对我有用的原因。我认为 Honza 是对的,这是与 ORM 层相关的问题。您可以运行以下示例
这是 linqpad 的示例:
void Main()
{
var Categories = new List<Category>() { new Category { CategoryName = "CatName", Products = new List<Product>() { new Product { Name = "ProductName1" } } } };
Func<Product, string> selector = p => p.Name;
var sb = new StringBuilder();
var query = Categories.Select(c => new
{
Products = c.Products.OrderBy(selector)
});
foreach (var x in query)
{
sb.AppendLine(x.Products.First().Name);
}
Console.WriteLine(sb.ToString());
Console.Read();
}
public class Product
{
public string Name { get; set; }
}
public class Category
{
public string CategoryName { get; set; }
public List<Product> Products { get; set; }
}
// 这里定义其他方法和类
这是 Visual Studio 控制台应用程序的版本:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var Categories = new List<Category>() { new Category { CategoryName = "CatName", Products = new List<Product>() { new Product { Name = "ProductName1" } } } };
Func<Product, string> selector = p => p.Name;
var sb = new StringBuilder();
var query = Categories.Select(c => new
{
Products = c.Products.OrderBy(selector)
});
foreach (var x in query)
{
sb.AppendLine(x.Products.First().Name);
}
Console.WriteLine(sb.ToString());
Console.Read();
}
public class Product
{
public string Name { get; set; }
}
public class Category
{
public string CategoryName { get; set; }
public List<Product> Products { get; set; }
}
}
}