【问题标题】:Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<Models>无法将类型 'System.Collections.Generic.List<AnonymousType#1>' 隐式转换为 'System.Collections.Generic.IEnumerable<Models>
【发布时间】:2013-05-15 16:24:19
【问题描述】:

当我为我添加 DefaultIfEmpty() 语句以右加入我的数据时,我的控制器出现异常。 .

这是我的控制器:

        public IEnumerable<APPLICANT> GetApplicant()
    {
        IEnumerable<APPLICANT> applicantdata = Cache.Get("applicants") as IEnumerable<APPLICANT>;
        IEnumerable<Profile> profiledata = Cache.Get("profiles") as IEnumerable<Profile>;


        if (applicantdata == null)
        {



            var applicantList = (from a in context.Profiles 
                                 join app in context.APPLICANTs
                                 on a.PROFILE_ID equals app.Profile_id into joined
                                 from j in joined.DefaultIfEmpty(new APPLICANT())
                                 select new
                                            {
                                               APPLICANT = j, 
                                               Profile = a,
                                            }).Take(1000).AsEnumerable();

                   applicantdata = applicantList.ToList();


            if (applicantdata.Any())
            {
                Cache.Set("applicants", applicantdata, 30);
            }
        }
        return applicantdata;

    }

这是我得到异常的那一行:

applicantdata = applicantList.ToList();

这是例外

无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.IEnumerable”。存在显式转换(您是否缺少演员表?)

【问题讨论】:

    标签: c# asp.net asp.net-mvc linq entity-framework


    【解决方案1】:

    对我来说这听起来像是编译时错误而不是异常,但无论如何...

    看看你的select子句:

    select new
    {
        APPLICANT = j, 
        Profile = a,
    }
    

    这只是一个匿名类型。您期望如何将其转换为APPLICANT?也许您只想要其中的APPLICANT 部分?这不是很清楚,但基本上你想要一个匿名类型,如果你想把它转换成一个命名类型的列表。如果您确实只希望申请人在j范围变量中,只需使用:

    select j
    

    (顺便说一句,最好尽量遵循 .NET 命名约定 - 类型名称和属性名称都不应该在 SHOUTY_CASE 中。)

    【讨论】:

    • 先生,谢谢。 .我只是希望它像这样......stackoverflow.com/questions/4497086/…
    • @EnriqueGil:不,你没有——因为那是使用匿名类型。您正在尝试为 IEnumerable&lt;APPLICANT&gt; 类型的变量赋值 - 所以您不能使用匿名类型。
    • 在设置为select j 后,它会闪烁NotSupportedException was unhandles by user code The entity or complex type 'Model.APPLICANT' cannot be constructed in a LINQ to Entities query.
    • @EnriqueGil:可能唯一的问题是您使用DefaultIfEmpty。目前尚不清楚在这种情况下您为什么要使用它。
    • @EnriqueGil:不,因为您甚至从未解释过您想要实现的目标。老实说,您似乎正试图通过从其他地方剪切和粘贴来“学习”LINQ。这不是一个好主意。你应该从基础开始学习,真正理解你的代码。
    猜你喜欢
    • 2013-05-14
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    相关资源
    最近更新 更多