entity-framework-4linq-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);
}

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?


Solution

  • 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;
        }
    }
    

    And then use it this way:

    result = result.Where(clsProfileDate.IsOlderThan(from));