Entity Framework 6, Database First, Linq and all that goodies!!!
I have the table "Customer" with one of its fields being the "DOB"
Using the VS2015 and EF, I have successfully generated the model which works fine
I use linq like
dim customers = context.Customers.toList
and the results are used as the datasource of the datagridview in windows forms.
But, to make things more interesting, I need to display a new, calculated field, "Age" as a column in the datagridview, which of course will be derived from the DOB and the today's day. To make the things even more interesting I would like to order the query results in an ascending age order.
I would prefer to avoid projections wanted to have a plain Customer class with all the necessary fields in it, even the calculated ones. Despite that if someone is good in projection his code would be welcome as well as it was difficult to me to do it that way as the function GetAgeByDates is not allowed by the compiler and sql
What I have tried:
I have created a separate file wanted to extend the partial class Customer which is auto-generated by the ADO.net EF Model. In this separate file, I have created a
Private _AgeOnDate As Integer
Public ReadOnly Property AgeOnDate As Integer
Get
Return _AgeOnDate
End Get
End Property
and
public Function GetAgeByDates(dob as Date, optional someDate As Date=Date.Now) As Integer
I needed this variable _AgeOnDate
And here is where the problem begins
I would ideally wanted to do something like
Public Overloads Property DOB As Date
Get
Return _DOB
End Get
Set(value As Date)
_DOB = value
_AgeOnDate = GetAgeFromDates(value, Date.Now)
End Set
End Property
So the Age will be calculated once the DOB is set and it will be stored in
_AgeOnDate
, so to be ready to be used in a linq query like
dim customers = context.Customers.OrderByDescending(Function(x) x.AgeOnDate).toList
But, the property is defined in the auto-generated file so I wouldn't like to alter it.
Of course someone would have suggested to order the list by Descending DOB, but that is not the issue. I need to, somehow, intercept the DOB setter and calculate the Age based on the newly set DOB. If this can be done, the same tactic will be applied on some other fiels which are not as easy to order as the DOB.
Also, I can NOT find a method like
OnDOBChanged
or atleast
OnPropertyChanged
to override and solve the problem. I look forward to hearing from you guys. Thanx a million for your time!