這是查詢工作正常,不會導致問題的工作示例。爲了簡單起見,我跳過了數據庫,直接進入內存中的對象,這可能是爲什麼它對我有用。我認爲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; }
}
}
}
告訴我..沒有'產品= c.Products.ToList()排序依據(選擇)'的作品嗎? –
@SimonWhitehead:不,它不起作用,同樣的例外。無論如何,即使調用ToList()工作,當產品在訂購之前被過濾時,這也不是一個好的解決方案,因爲訂購將發生在內存中。 – user2604373
這對我來說很好。你能提供一個可以拋出這個異常的工作示例嗎? –