2013-12-22 30 views
1

我想有一個遞增的獨立組各項目(如描述here一個int屬性,因爲報價所需的可訪問樣/person/quote/1..2..3/person/quote/1..5..10實體框架遞增的索引屬性組

Quote Person Index 
Lorem Smith 1 
Ipsum Smith 2 
Loremi Lewis 1 
Ipsumi Lewis 2 

在這個問題使用代碼EF:

var query = _data.Quotes 
    .GroupBy(x => x.Person.Name) 
    .Select 
    (
     x => x.Select((y, i) => new { y.Text, y.Person.Name, Index = i + 1 }) 
    ) 
    .SelectMany(x => x); 

但EF不能分析它,並返回NotSupportedException例外:

LINQ to Entities does not recognize the method 
System.Collections.Generic.IEnumerable`1[<>f__AnonymousType9`2[System.String,System.Int32]] Select[Quote,<>f__AnonymousType9`2](System.Collections.Generic.IEnumerable`1[App.Models.Quote], System.Func`3[App.Models.Quote,System.Int32,<>f__AnonymousType9`2[System.String,System.Int32]]) and this method cannot be translated into a store expression 
+0

添加'.ToLower()'每串查詢並再次運行 – Ani

+1

只檢索通過在查詢中插入一個.ToList到Linq to Entities仍然可以理解的位置來分組數據。在此之後,你在LINQ to Objects並可以應用索引。 – Dabblernl

回答

2

由於Dabblernl的評論此代碼工作:

var query = _data.Quotes 
    .GroupBy(x => x.Person.Name) 
    .ToList() 
    .Select 
    (
     x => x.Select((y, i) => new { y.Person.Name, y.Text, Index = i + 1 }) 
    ) 
    .SelectMany(x => x); 
+0

它會影響性能嗎?與ToList()我檢索所有列等有沒有更好的解決方案? – netdis

+0

措施,你會知道的! :-)您可以嘗試在調用ToList之前將這些值投影(選擇)到只包含您需要的字段的自定義類中。 – Dabblernl

0

查詢:

var query = _data.Quotes 
    .GroupBy(x => x.Person.Name.ToLower()) 
    .Select 
    (
    x => x.Select((y, i) => new { y.Text.ToLower(), y.Person.Name.ToLower(), Index = i + 1 }) 
) 
    .SelectMany(x => x); 
+0

匿名類型成員聲明程序無效。匿名類型成員必須聲明爲成員分配,簡單名稱或成員訪問權限。即使當我使用Name = y.Person.Name.ToLower()仍然與問題中描述的NotSupportedException相同時。 – netdis

+0

你能首先檢查字符串是空還是空? – Ani