【问题标题】:System.NotSupportedException:The entity or complex type Model.APPLICANT cannot be constructed in a LINQ to Entities querySystem.NotSupportedException:无法在 LINQ to Entities 查询中构造实体或复杂类型 Model.APPLICANT
【发布时间】:2013-05-21 17:21:04
【问题描述】:

目前正在修复我的代码,直到发生此异常

System.NotSupportedException: The entity or complex type Model.APPLICANT' cannot be constructed in a LINQ to Entities query

这是我的控制器:

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


    if (applicantdata == null)
    {

        var applicantList = (from app in context.APPLICANTs
                             join a in context.Profiles
                             on app.Profile_id equals a.PROFILE_ID into output
                             from j in output.DefaultIfEmpty()
                             select new APPLICANT() { APPLICANT_ID = app.APPLICANT_ID, APPLICANT_LastName = (j == null ? app.APPLICANT_LastName : j.Applicant_LASTNAME) }).Take(1000).AsEnumerable().AsQueryable();

        applicantdata = applicantList.Where(v => !String.IsNullOrEmpty(v.APPLICANT_LastName)).AsEnumerable();



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

}

异常出现在这一行

if (applicantdata.Any())

我希望有人可以建议或找到解决此问题的方法。 .谢谢

【问题讨论】:

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


【解决方案1】:

由于您无法在查询中创建非 EF 类型的新实例,您可以将查询分成两部分。

首先你得到数据

var data = from app in context.APPLICANTs
           join a in context.Profiles
             on app.Profile_id equals a.PROFILE_ID into output
           from j in output.DefaultIfEmpty()
           select new { 
             Id = app.APPLICANT_ID, 
             LastName = 
               (j == null ? app.APPLICANT_LastName : j.Applicant_LASTNAME) 
           };

var applicantData = data.Take(1000)
  .Where(v => !String.IsNullOrEmpty(v.APPLICANT_LastName));

然后你初始化实例

var applicants = (from a in applicantData
                  select new APPLICANT() { 
                    APPLICANT_ID = a.Id, 
                    APPLICANT_LastName = a.LastName
                  }
                 ).AsEnumerable();

【讨论】:

  • 'AnonymousType#1' does not contain a definition for 'Applicant_LastName' and no extension method 'Applicant_LastName' accepting a first argument of type 'AnonymousType#1' could be found (are you missing a using directive or an assembly reference?) IsNullOrEmpty(v.Applicant_Lastname) 出错
  • .Where(v =&gt; !String.IsNullOrEmpty(v.APPLICANT_LastName)); 更改为.Where(v =&gt; !String.IsNullOrEmpty(v.LastName))
  • 谢谢先生。 .但是我该如何解决它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-11
  • 2017-05-31
  • 2015-02-06
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
相关资源
最近更新 更多