LINQ to Entities不支持指定的类型成员。仅支持初始值设定项,实体成员和实体导航属性

LINQ to Entities不支持指定的类型成员。仅支持初始值设定项,实体成员和实体导航属性

var result =
    (from bd in context.tblBasicDetails     from pd in context.tblPersonalDetails.Where(x => x.UserId == bd.UserId).DefaultIfEmpty()
     from opd in context.tblOtherPersonalDetails.Where(x => x.UserId == bd.UserId).DefaultIfEmpty()
     select new clsProfileDate()
     {
         DOB = pd.DOB     });foreach (clsProfileDate prod in result){
    prod.dtDOB = !string.IsNullOrEmpty(prod.DOB) ? Convert.ToDateTime(prod.DOB) : DateTime.Today;
    int now = int.Parse(DateTime.Today.ToString("yyyyMMdd"));
    int dob = int.Parse(prod.dtDOB.ToString("yyyyMMdd"));
    string dif = (now - dob).ToString();
    string age = "0";
    if (dif.Length > 4)
    age = dif.Substring(0, dif.Length - 4);
    prod.Age = Convert.ToInt32(age);}GetFinalResult(result);

protected void GetFinalResult(IQueryable<clsProfileDate> result){
    int from;
    bool bfrom = Int32.TryParse(ddlAgeFrom.SelectedValue, out from);
    int to;
    bool bto = Int32.TryParse(ddlAgeTo.SelectedValue, out to);

    result = result.AsQueryable().Where(p => p.Age >= from);}

我在这里得到一个例外:

LINQ to Entities不支持指定的类型成员“Age”。仅支持初始值设定项,实体成员和实体导航属性。

如果Age不在数据库中,则是我在clsProfileDate类中创建的属性,用于从DOB计算Age。对此有何解决方案?


牧羊人nacy
浏览 1970回答 3
3回答

慕盖茨4494581

您不能使用未映射到Where表达式中的数据库列的属性。您必须基于映射属性构建表达式,例如:var date = DateTime.Now.AddYears(-from);result = result.Where(p => date >= p.DOB);// you don't need `AsQueryable()` here because result is an `IQueryable` anyway作为未映射Age属性的替代,您可以将此表达式提取到静态方法中,如下所示:public class clsProfileDate{&nbsp; &nbsp; // ...&nbsp; &nbsp; public DateTime DOB { get; set; } // property mapped to DB table column&nbsp; &nbsp; public static Expression<Func<clsProfileDate, bool>> IsOlderThan(int age)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var date = DateTime.Now.AddYears(-age);&nbsp; &nbsp; &nbsp; &nbsp; return p => date >= p.DOB;&nbsp; &nbsp; }}然后以这种方式使用它:result = result.Where(clsProfileDate.IsOlderThan(from));

德玛西亚99

很多人都会说这是一个错误的答案,因为这不是最佳实践,但你也可以在你的位置之前将其转换为List。result&nbsp;=&nbsp;result.ToList().Where(p&nbsp;=>&nbsp;date&nbsp;>=&nbsp;p.DOB);Slauma的答案更好,但这也可行。这会花费更多,因为ToList()将对数据库执行查询并将结果移动到内存中。
打开App,查看更多内容
随时随地看视频慕课网APP