EntityFramework 4, DbSet, and ObjectContext

a few days ago I read a tutorial about the GenericRepository and Unit of Work templates 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 the EntityFramework CTP4 package installed. (I can not use EF 5).

I want to create a shared repository for my project, but I am stuck on this line:

this.dbSet = context.Set<TEntity>();

I know that this line does not work, because using ObjectContext in my project and database is the first approach. How can I handle this? Can I copy the shared repository without transferring to the first code (which is not an option in my case)?

+5
source share
2 answers

This is the equivalent of an ObjectContext:

this.dbSet = context.CreateObjectSet<TEntity>();

Now it creates ObjectSet<TEntity>, not DbSet<TEntity>, but for your template you can use it in the same way.

UPDATE

The class ObjectSetdoes not have a utility method that matches the method Find()for DbSet. In order to get by key you had to build EntityKeyand use ObjectContext.GetEntityByKey(), unfortunately, this is not a very simple thing to do.

There is really no easy way to handle this that I found. In my case, what I did was to base all my entities from a common class (using custom T4 templates to generate classes from the model). And then I can add a general restriction to my repositories, for example:

public class MyRepository<TEntity> where TEntity : MyEntityBaseClass

Id, , :

return myObjectSet.SingleOrDefault(x => x.Id == myId);

, , .

+7

1. DbContextGenerator :

DbContextGenerator template

2. , .edmx.

Code generation tool

3. GenericRepository, .

+4

All Articles