LINQ to Entities不支持指定的类型成员。只支持初始化器,实体成员和实体导航属性 [英] The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported
问题描述
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。
仅支持初始化,实体成员和实体导航属性
。
The specified type member "Age" is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
其中年龄不在数据库中这是我在clsProfileDate类中创建的属性,用于从DOB计算Age。任何解决方案?
Where Age is not in database it is property I created in clsProfileDate class to calculate Age from DOB. Any solution to this?
推荐答案
您不能使用未映射到中的数据库列的属性其中
表达式。您必须基于映射属性构建表达式,如:
You cannot use properties that are not mapped to a database column in a Where
expression. You must build the expression based on mapped properties, like:
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
为了替代您未映射的年龄
属性,您可以将此表达式解压缩成静态方法,如下所示:
As a replacement for your not mapped Age
property you can extract this expression into a static method like so:
public class clsProfileDate
{
// ...
public DateTime DOB { get; set; } // property mapped to DB table column
public static Expression<Func<clsProfileDate, bool>> IsOlderThan(int age)
{
var date = DateTime.Now.AddYears(-age);
return p => date >= p.DOB;
}
}
然后以这种方式使用:
result = result.Where(clsProfileDate.IsOlderThan(from));
这篇关于LINQ to Entities不支持指定的类型成员。只支持初始化器,实体成员和实体导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!