可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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 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); }
Here I am getting an exception:
The specified type member "Age" is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
Where Age is not in database it is property I created in clsProfileDate class to calculate Age from DOB. Any solution to this?
回答1:
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> IsOlderThan(int age) { var date = DateTime.Now.AddYears(-age); return p => date >= p.DOB; } }
And then use it this way:
result = result.Where(clsProfileDate.IsOlderThan(from));
回答2:
A lot of people are going to say this is a bad answer because it is not best practice but you can also convert it to a List before your where.
result = result.ToList().Where(p => date >= p.DOB);
Slauma's answer is better, but this would work as well. This cost more because ToList() will execute the Query against the database and move the results into memory.
回答3:
You will also get this error message when you accidentally forget to define a setter for a property. For example:
public class Building { public string Description { get; } } var query = from building in context.Buildings select new { Desc = building.Description }; int count = query.ToList();
The call to ToList will give the same error message. This one is a very subtle error and very hard to detect.