DbSet, EntityFramework 4, and ObjectContext

entity-framework objectcontext


I read a lesson about GenericRepository and the 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 a few days ago. I have the EntityFramework CTP4 package installed and I utilize web forms. (I am unable to use EF 5)

I got blocked at the following line when trying to write a generic repository for my project:

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

Due to the usage of ObjectContext in my project and database-first methodology, I am aware that this line is ineffective. How do I handle it? Can I create a generic repository without first migrating to code (which, in my situation, is not an option)?

3/22/2012 12:51:38 PM

Accepted Answer

The equivalent for ObjectContext is as follows:

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

This now results in anObjectSet<TEntity> alternative to aDbSet<TEntity> but you may use it the same way for your design.


The ObjectSet class lacks a utility function that corresponds to theFind() approach to theDbSet You would need to create an encryption key in order to "Get by key."EntityKey Sadly, using the ObjectContext.GetEntityByKey() is not something that can be done easily.

I haven't really found a straightforward approach to this. In my situation, I've created a single class from which I've derived all of my things (using custom T4 templates to generate the classes from the model). Then I may include a general restriction in my repository, like as:

public class MyRepository<TEntity> where TEntity : MyEntityBaseClass

My common base class also has anId property that all entities inherit, allowing me to easily:

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

There may be additional strategies, which might make an excellent subject for a different inquiry.

3/22/2012 7:43:25 PM

Popular Answer

You want to include theDbContextGenerator to your Visual Studio templates as a template:

DbContextGenerator template

2. After that, be careful to remove your computer's default generating tool..edmx file.

Code generation tool

3. Currently, you may put theGenericRepository the way you like.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow