2011-11-29 52 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