简体   繁体   English

Linq-如何收集匿名类型作为函数的结果

[英]Linq - How to collect Anonymous Type as Result for a Function

I use c# 4 asp.net and EF 4. I'm precompiling a query, the result should be a collection of Anonymous Type. 我使用c#4 asp.net和EF4。我正在预编译查询,结果应该是匿名类型的集合。

At the moment I use this code. 目前,我使用此代码。

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));

I suspect the RETURN for the FUNCTION Dynamic does not work properly and I get this error 我怀疑FUNCTION Dynamic的RETURN无法正常工作,并且出现此错误

Sequence contains more than one element enter code here . 序列包含多个元素,请enter code here

I suppose I need to return for my function a Collection of Anonymous Types... 我想我需要为我的函数返回一个匿名类型集合...

Do you have any idea how to do it? 你有什么想法吗? What I'm doing wrong? 我做错了什么? Please post a sample of code thanks! 请发表示例代码,谢谢!

Update: 更新:

    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));

You should not return an anonymous type from a method. 您不应该从方法中返回匿名类型。 Create a concrete type to hold whatever data is currently held in the anonymous type and return that instead. 创建一个具体类型以容纳匿名类型中当前包含的所有数据,然后返回该数据。

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

where: 哪里:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM