Is it possible in Entity Framework to make a custom converter method for converting an integer into an entity through an explicit conversion?
I did some research on this, and I don’t know where to start.
Here’s an example of what I’m trying to do.
int activeTeacherId = 38;
Teacher activeTeacher = (Teacher)activeTeacherId;
Edit 1 After some quick research, I figured out that I probably need to do something with the EntityObject if I need everything to be truly generic and flexible. However, I’m not sure how.
Edit 2 From my own experience, I managed to create the following code. However, for obvious reasons, I can’t get “this” inside a static context.
If I could just somehow get the type of the object that it’s being converted into (since it’s not always being converted into an EntityObject, but sometimes a Person or a Teacher), then it would theoretically work.
public class EntityObject : System.Data.Objects.DataClasses.EntityObject
{
public static explicit operator EntityObject(int id)
{
var container = ModelContainer.Instance;
var thisType = this.GetType(); //this can't be done from a static context, so how do we retrieve the type that we are converting into?
var containerType = typeof (ModelContainer);
dynamic setProperty = typeof (ModelContainer).GetProperty(thisType.Name + "Set");
ObjectSet<dynamic> set = setProperty.GetValue(container);
return set.FirstOrDefault(o => o.Id == id);
}
}
I finally did it! Based on Peter’s suggestions (see his comment on my question), I have created an extension method on “int” which allows me to perform the actions I am looking for.
I’m quite proud of this algorithm since I figured out most of it myself. It involves some serious reflection stuff, dynamic creation of lambda expressions, and the evaluation of them. But it works!
Any suggestions to make it shorter or better would be appreciated.