2011-11-29 51 views
1

我使用c#4 asp.net和EF 4.我預編譯查詢,結果應該是匿名類型的集合。Linq - 如何收集匿名類型作爲函數的結果

此刻我使用此代碼。

public static readonly Func<CmsConnectionStringEntityDataModel, string, dynamic>  
queryContentsList = 
CompiledQuery.Compile<CmsConnectionStringEntityDataModel, string, dynamic> 
(
    (ctx, TypeContent) => ctx.CmsContents.Where(c => c.TypeContent == TypeContent 
& c.IsPublished == true & c.IsDeleted == false) 
     .Select(cnt => new 
     { 
     cnt.Title, 
     cnt.TitleUrl, 
     cnt.ContentId, 
     cnt.TypeContent, cnt.Summary 
     } 
      ) 
    .OrderByDescending(c => c.ContentId)); 

我懷疑的功能Dynamic的回報率並不能正常工作,我得到這個錯誤

序列包含多個元素enter code here

我想我需要回到我的功能匿名類型的集合...

你有任何想法如何做到這一點?我做錯了什麼?請張貼代碼示例謝謝!

更新:

public class ConcTypeContents 
     { 
      public string Title { get; set; } 
      public string TitleUrl { get; set; } 
      public int ContentId { get; set; } 
      public string TypeContent { get; set; } 
      public string Summary { get; set; } 
     } 

     public static readonly Func<CmsConnectionStringEntityDataModel, string, ConcTypeContents> queryContentsList = 
CompiledQuery.Compile<CmsConnectionStringEntityDataModel, string, ConcTypeContents>(
    (ctx, TypeContent) => ctx.CmsContents.Where(c => c.TypeContent == TypeContent & c.IsPublished == true & c.IsDeleted == false) 
     .Select(cnt => new ConcTypeContents { cnt.Title, cnt.TitleUrl, cnt.ContentId, cnt.TypeContent, cnt.Summary }).OrderByDescending(c => c.ContentId)); 

回答

5

你不應該從方法返回一個匿名類型。創建一個具體類型來存放匿名類型中的所有數據,然後返回。

... 
.Select(cnt => 
    new ConcType{ 
     Title = cnt.Title, 
     TitleUrl = cnt.TitleUrl, 
     ContentId = cnt.ContentId, 
     TypeContent = cnt.TypeContent, 
     Summary = cnt.Summary }) 
... 

其中:

class ConcType 
{ 
    public string Title {get; set;} 
    //etc... 
} 
+0

我得到這個錯誤..... ConcType如果你更新的代碼添加到這個問題還沒有實現「System.Collections.IEnumerable」 – GibboK

+0

,它可能是更容易告訴你發生了什麼事。 – spender

+0

謝謝你,我更新了代碼,如果你有時間請告訴我。 – GibboK