few days ago i read tutorial about GenericRepository and Unit Of Work patterns http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application. I use web forms and i have EntityFramework CTP4 package installed. (I can't using EF 5).
I want to code generic repository for my project but i was stuck at this line:
this.dbSet = context.Set<TEntity>();
I know that this line doesn't work because a use ObjectContext in my project and database first approach. How can i deal with it? Can I code generic repository without migration to code first (which is not an option in my case) ?
Best Answer
This is the equivalent for ObjectContext:
Now this creates an
ObjectSet<TEntity>
rather than aDbSet<TEntity>
, but for your pattern you can use it in the same way.UPDATE
The
ObjectSet
class does not have a utility method like that matches theFind()
method of theDbSet
. In order to "Get by key" you would need to construct anEntityKey
and use theObjectContext.GetEntityByKey()
, unfortunately that's not a really simple thing to do.There really isn't a simple way to tackle this, that I've found. In my case what I've done is to base all of my entities from a common class (using custom T4 templates to generate the classes from the model). And then I can add a generic constraint to my repositories, like:
And then my common base class has an
Id
field which is inherited by all the entities so I can can simply do:I'm sure there are other approaches, that might be a good topic for another question.