简体   繁体   中英

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.

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

Sequence contains more than one element 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...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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