【问题标题】:Linq - How to collect Anonymous Type as Result for a FunctionLinq - 如何收集匿名类型作为函数的结果
【发布时间】:2011-11-29 17:47:22
【问题描述】:

我使用 c# 4 asp.net 和 EF 4。我正在预编译一个查询,结果应该是匿名类型的集合。

目前我使用此代码。

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

【问题讨论】:

    标签: c# linq entity-framework anonymous-types


    【解决方案1】:

    您不应该从方法返回匿名类型。创建一个具体类型来保存匿名类型中当前保存的任何数据,然后将其返回。

    ...
    .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...
    }
    

    【讨论】:

    • 我得到这个错误...... ConcType 它没有实现'System.Collections.IEnumerable'
    • 如果您将更新后的代码添加到问题中,可能更容易告诉您发生了什么。
    • 谢谢spender,我更新了代码,如果你有时间请告诉我。
    • 呃,你可以从一个方法返回一个匿名类型,你只是不能返回它的强类型。如果方法签名是返回object 或(如这里)dynamicreturn new { a = 5 }; 工作得很好。相反,原始错误和评论都表明 sequencesindividual objects 之间存在混淆。
    • AakashM 我明白你的意思。你有实用的方法来解决它吗?谢谢
    猜你喜欢
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多