51

I am about to implement an Entity Framework 6 design with a repository and unit of work.

There are so many articles around and I'm not sure what the best advice is: For example I realy like the pattern implemented here: for the reasons suggested in the article here

However, Tom Dykstra (Senior Programming Writer on Microsoft's Web Platform & Tools Content Team) suggests it should be done in another article: here

I subscribe to Pluralsight, and it is implemented in a slightly different way pretty much every time it is used in a course so choosing a design is difficult.

Some people seem to suggest that unit of work is already implemented by DbContext as in this post, so we shouldn't need to implement it at all.

I realise that this type of question has been asked before and this may be subjective but my question is direct:

I like the approach in the first (Code Fizzle) article and wanted to know if it is perhaps more maintainable and as easily testable as other approaches and safe to go ahead with?

Any other views are more than welcome.

davy
  • 4,474
  • 10
  • 48
  • 71
  • 3
    I'm exactly on the same situation use Repo/UOF or not to use and I have read so many blogs and I'm more confused then ever :), I'm going to go what MS articles http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application I have already spent enough time finding out and best practice and I guess there is no right answer. – Nick Kahn Jul 23 '14 at 17:19

7 Answers7

45

@Chris Hardie is correct, EF implements UoW out of the box. However many people overlook the fact that EF also implements a generic repository pattern out of the box too:

var repos1 = _dbContext.Set<Widget1>();
var repos2 = _dbContext.Set<Widget2>();
var reposN = _dbContext.Set<WidgetN>();

...and this is a pretty good generic repository implementation that is built into the tool itself.

Why go through the trouble of creating a ton of other interfaces and properties, when DbContext gives you everything you need? If you want to abstract the DbContext behind application-level interfaces, and you want to apply command query segregation, you could do something as simple as this:

public interface IReadEntities
{
    IQueryable<TEntity> Query<TEntity>();
}

public interface IWriteEntities : IReadEntities, IUnitOfWork
{
    IQueryable<TEntity> Load<TEntity>();
    void Create<TEntity>(TEntity entity);
    void Update<TEntity>(TEntity entity);
    void Delete<TEntity>(TEntity entity);
}

public interface IUnitOfWork
{
    int SaveChanges();
}

You could use these 3 interfaces for all of your entity access, and not have to worry about injecting 3 or more different repositories into business code that works with 3 or more entity sets. Of course you would still use IoC to ensure that there is only 1 DbContext instance per web request, but all 3 of your interfaces are implemented by the same class, which makes it easier.

public class MyDbContext : DbContext, IWriteEntities
{
    public IQueryable<TEntity> Query<TEntity>()
    {
        return Set<TEntity>().AsNoTracking(); // detach results from context
    }

    public IQueryable<TEntity> Load<TEntity>()
    {
        return Set<TEntity>();
    }

    public void Create<TEntity>(TEntity entity)
    {
        if (Entry(entity).State == EntityState.Detached)
            Set<TEntity>().Add(entity);
    }

    ...etc
}

You now only need to inject a single interface into your dependency, regardless of how many different entities it needs to work with:

// NOTE: In reality I would never inject IWriteEntities into an MVC Controller.
// Instead I would inject my CQRS business layer, which consumes IWriteEntities.
// See @MikeSW's answer for more info as to why you shouldn't consume a
// generic repository like this directly by your web application layer.
// See http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91 and
// http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92 for more info
// on what a CQRS business layer that consumes IWriteEntities / IReadEntities
// (and is consumed by an MVC Controller) might look like.
public class RecipeController : Controller
{
    private readonly IWriteEntities _entities;

    //Using Dependency Injection 
    public RecipeController(IWriteEntities entities)
    {
        _entities = entities;
    }

    [HttpPost]
    public ActionResult Create(CreateEditRecipeViewModel model)
    {
        Mapper.CreateMap<CreateEditRecipeViewModel, Recipe>()
            .ForMember(r => r.IngredientAmounts, opt => opt.Ignore());

        Recipe recipe = Mapper.Map<CreateEditRecipeViewModel, Recipe>(model);
        _entities.Create(recipe);
        foreach(Tag t in model.Tags) {
            _entities.Create(tag);
        }
        _entities.SaveChanges();
        return RedirectToAction("CreateRecipeSuccess");
    }
}

One of my favorite things about this design is that it minimizes the entity storage dependencies on the consumer. In this example the RecipeController is the consumer, but in a real application the consumer would be a command handler. (For a query handler, you would typically consume IReadEntities only because you just want to return data, not mutate any state.) But for this example, let's just use RecipeController as the consumer to examine the dependency implications:

Say you have a set of unit tests written for the above action. In each of these unit tests, you new up the Controller, passing a mock into the constructor. Then, say your customer decides they want to allow people to create a new Cookbook or add to an existing one when creating a new recipe.

With a repository-per-entity or repository-per-aggregate interface pattern, you would have to inject a new repository instance IRepository<Cookbook> into your controller constructor (or using @Chris Hardie's answer, write code to attach yet another repository to the UoW instance). This would immediately make all of your other unit tests break, and you would have to go back to modify the construction code in all of them, passing yet another mock instance, and widening your dependency array. However with the above, all of your other unit tests will still at least compile. All you have to do is write additional test(s) to cover the new cookbook functionality.

danludwig
  • 46,965
  • 25
  • 159
  • 237
  • 2
    Your solution sounds very interesting. Wish you could publish a sample application as it's difficult with just code snippets. – Samantha J T Star Feb 19 '14 at 07:20
  • @SamanthaJ I am working on one, just have not published it to GH yet. This isn't really that *structurally* different from the repository-per-entity or repository-per-aggregate pattern that you are used to. You are still defining interfaces that get implemented by EF. The difference is the interface signatures, and where you draw the seams / boundaries for the methods. The solution I am proposing here uses generics in the method calls rather than in the repository interfaces & implementations. This way, you end up with a repository-per-model (where model includes all aggregates & entities). – danludwig Feb 25 '14 at 04:14
  • 2
    Interesting approach, any news on the update with code samples? :-) – janhartmann Mar 15 '14 at 11:49
  • @meep, have a look at my github account. I was going to mail you, but wanted to polish some things first. They are still not polished, but you can look. – danludwig Mar 15 '14 at 20:28
  • When I tried same concept its giving error like The entity type Receipe is not part of the model for the current context. – Jalpesh Vadgama Apr 23 '14 at 08:39
  • Its seems that be interesting. could you please send me some code samples, too? – Masoud Jun 14 '14 at 10:41
  • @Masoud look for the Tripod project in my github account. – danludwig Jun 14 '14 at 15:33
  • I like your interfaces they are nice and simple and I have done similar things in projects I have worked on - actually yours are a lot cleaner. However I would like to point out that separating Create and Update makes sense when coming from a Database perspective but not always when you are on the calling side with un-proxied EF objects, for instance web applications. Instead I think the ORM should figure out if it is create or update in the context of the Unit of Work. We should only need to have a method for pushing objects into the Repository context - Add instead of Create & Update. – agilejoshua Jun 25 '14 at 21:41
  • @josant I partially disagree. Create and update are not merely database terms, they are terms we use in everyday life, web apps included. HTTP even has notions of create and update -- it's the difference between a POST and a PUT. The question comes to identification. In a web app, we may have a url like /resources/1 or /resources/name where 1 and name are unique items within a set of resources. How does that ID get generated? If the user creates it then the web app knows it, and can only do PUTs (updates). If the ID needs to be generated though, then each operation needs a different signature. – danludwig Jun 26 '14 at 16:32
  • REST and Repository patterns attempt to solve completely different problems. But all the same PUT in REST is not update, it is create or update and is idempotent. Whereas in at least SQL create and update are two completely different operations, using the wrong one will lead to en error. My point with proposing just using Add in an abstract repository is that in a lot of scenarios id generation can be distributed (Guids, Snowflake) and forcing the caller of the repository to know if the specific id already exists in the data store pushes us into sql thinking instead of abstracting it. – agilejoshua Jun 28 '14 at 13:57
  • @josant that is a really good point. I never meant to say "PUT is an update", but was trying to point out the possible difference of method signatures in the API -- since one op may not provide an id, whereas the other will. Since these interfaces pass a single generic entity arg they always have some kind of ID, and one could replace them with a single method that imitates PUT (create or update). However, doesn't this mean you are pushing rest semantics onto your repos layer? Do you have a command / query layer between the web and data store, or are you injecting your repos into controllers? – danludwig Jun 30 '14 at 14:41
  • In this example you're assuming that your Domain Entities and your Data Entities are the same. That works for some simple systems where they can operate under a CRUD approach. If you are implementing DDD with CQRS for example, this will fall flat on your face. – Pepito Fernandez Jul 15 '14 at 19:26
  • @danludwig Do you have any post describing the Tripod project? It would really help in understanding the project. – Charanraj Golla Sep 02 '14 at 03:42
  • Out of all the answers here, this one sums everything up quite nicely. I'm used to working with a custom repository pattern, however I'm building an MVC website so was weighing up whether I should continue down that path or not. This essentially swayed my vote into using the out of the box version in EF6. – Damian Mar 12 '16 at 13:19
45

I'm (not) sorry to say that the codefizzle, Dyksta's article and the previous answers are wrong. For the simple fact that they use the EF entities as domain (business) objects, which is a big WTF.

Update: For a less technical explanation (in plain words) read Repository Pattern for Dummies

In a nutshell, ANY repository interface should not be coupled to ANY persistence (ORM) detail. The repo interface deals ONLY with objects that makes sense for the rest of the app (domain, maybe UI as in presentation). A LOT of people (with MS leading the pack, with intent I suspect) make the mistake of believing that they can reuse their EF entities or that can be business object on top of them.

While it can happen, it's quite rare. In practice, you'll have a lot of domain objects 'designed' after database rules i.e bad modelling. The repository purpose is to decouple the rest of the app (mainly the business layer) from its persistence form.

How do you decouple it when your repo deals with EF entities (persistence detail) or its methods return IQueryable, a leaking abstraction with wrong semantics for this purpose (IQueryable allows you to build a query, thus implying that you need to know persistence details thus negating the repository's purpose and functionality)?

A domin object should never know about persistence, EF, joins etc. It shouldn't know what db engine you're using or if you're using one. Same with the rest of the app, if you want it to be decoupled from the persistence details.

The repository interface know only about what the higher layer know. This means, that a generic domain repository interface looks like this

public interface IStore<TDomainObject> //where TDomainObject != Ef (ORM) entity
{
   void Save(TDomainObject entity);
   TDomainObject Get(Guid id);
   void Delete(Guid id);
 }

The implementation will reside in the DAL and will use EF to work with the db. However the implementation looks like this

public class UsersRepository:IStore<User>
 {
   public UsersRepository(DbContext db) {}


    public void Save(User entity)
    {
       //map entity to one or more ORM entities
       //use EF to save it
    }
           //.. other methods implementation ...

 }

You don't really have a concrete generic repository. The only usage of a concrete generic repository is when ANY domain object is stored in serialized form in a key-value like table. It isn't the case with an ORM.

What about querying?

 public interface IQueryUsers
 {
       PagedResult<UserData> GetAll(int skip, int take);
       //or
       PagedResult<UserData> Get(CriteriaObject criteria,int skip, int take); 
 }

The UserData is the read/view model fit for the query context usage.

You can use directly EF for querying in a query handler if you don't mind that your DAL knows about view models and in that case you won't be needing any query repo.

Conclusion

  • Your business object shouldn't know about EF entities.
  • The repository will use an ORM, but it never exposes the ORM to the rest of the app, so the repo interface will use only domain objects or view models (or any other app context object that isn't a persistence detail)
  • You do not tell the repo how to do its work i.e NEVER use IQueryable with a repo interface
  • If you just want to use the db in a easier/cool way and you're dealing with a simple CRUD app where you don't need (be sure about it) to maintain separation of concerns then skip the repository all together, use directly EF for everything data. The app will be tightly coupled to EF but at least you'll cut the middle man and it will be on purpose not by mistake.

Note that using the repository in the wrong way, will invalidate its use and your app will still be tightly coupled to the persistence (ORM).

In case you believe the ORM is there to magically store your domain objects, it's not. The ORM purpose is to simulate an OOP storage on top of relational tables. It has everything to do with persistence and nothing to do with domain, so don't use the ORM outside persistence.

Linky
  • 605
  • 8
  • 24
MikeSW
  • 16,140
  • 3
  • 39
  • 53
  • I like this answer. I often think of the ORM an implementation of the storage abstraction. – Chalky Apr 01 '14 at 20:21
  • 3
    @MikeSW when you say "NEVER use IQueryable with a repo interface", are you implying that I should bring all data over the wire and when it is mapped to my domain objects then select the records that I need? That does not sound right... am I missing something? – Miguel May 13 '14 at 20:01
  • 1
    @Mike Yes, you are. You are talking about building queries which should be an implementation detail not exposed by the abstraction. The repo's client should just tell what and maybe provide some criteria. IQueryable means the client is building the query itself thus making the repository useless and exposing internal details. Besides it will work with only 1 data source. If you need to get data from 2 different sources then you're out of luck. – MikeSW May 13 '14 at 22:29
  • 1
    Would you have an example of this implemented top to bottom somewhere like github ? – LaserBeak May 14 '14 at 12:29
  • 1
    I second LaserBeak. I definitively want to see MikeSW's approach working. I see a huge benefit using this approach on big projects. – Miguel May 14 '14 at 16:51
  • 4
    All the required code is already in the answer. Is nothing mystical about it, it's that simple. – MikeSW May 14 '14 at 20:32
  • 2
    Does this mean that when EF pulls entities out of the database they should then be mapped to domain objects for use in controllers and domain layer ? Also when saving/updating all viewmodels used by action/api methods will first have to be mapped to domain objects and then passed to the repo ? – LaserBeak May 29 '14 at 00:59
  • I agree with your views on having criteria objects so that persistence details are removed from the calling application, but I think generally people should use IQueryable. The IQueryable interface is not tied to any specific persistence technology and the LINQ queries your write (even query expressions) can only operate on properties and objects which are contained in you business objects so there is no leaking of the storage technology through IQueryable. But all too often Repository implementations themselves leak everything about the persistence layer! danludwig's answer is pretty good. – agilejoshua Jun 25 '14 at 20:52
  • This is a very interesting answer (and article) which definitely has its merits - especially the parts about the query criteria pattern. What I left out of my answer for brevity is that I use the patterns in my answer with a CQRS command/query pipeline. So in reality, @MikeSW is right here. In my applications, the Command and Query objects are my business objects, and get mapped to EF entities before stored / returned. Comman/Query handler methods effectively become repository methods, converting `IQueryable` to `PagedResult`, `T[]`, or whatever... without repository interface explosion. – danludwig Jul 10 '14 at 13:33
  • They removed the section about repository and unit of work for Entity Framework 6: [link](http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/advanced-entity-framework-scenarios-for-an-mvc-web-application#repo) – Gorgi Rankovski Sep 09 '14 at 23:01
  • 2
    While you point out interesting things, saying that it is a big WTF to use EF entities as business objects means that you really don't understand EF. This is the sole purpose of EF. It abstracts away the mapping of your business entities to a database engine structures. It is true that you might need to add some additional properties or classes (that don't really have meaning in business processes) to satisfy the structure of your database, still I am happier with that, rather than having to create mirror classes of my business objects that only leave in the data access layer. – Gorgi Rankovski Sep 09 '14 at 23:13
  • 3
    The point of _ANY_ ORM is to map **objects** to tables and back. That's it. Not all objects are easily mapped and when dealing with domain objects (rich in behaviour not simple data structures). And when things get complicated you have to choose who drives who. And most devs choose persistence (EF) driving the domain instead of the opposite. So DDD becomes Database driven development. – MikeSW Sep 21 '14 at 16:20
  • Could we break the Save method of the `IStore` interface into Insert and Add? That would ease repository implementation. It looks BL knows when it is a new or modified domain object. With this only Save method in DAL we need to determine somehow those things with DB query for existing or not entity I guess. Thanks! – Artyom Nov 24 '14 at 10:57
  • @Artjom Sure we can. Some devs prefer explicit Add/Save , other just one Save. – MikeSW Nov 24 '14 at 14:52
  • 1
    Maybe a bit late in the game, but I second @GorgiRankovski that you don't really get EF. I agree that DbContext is not really a UoW, and DbSets are not really Repositories. But your repo doesn't need to deal with EF entities at all. You write POCO's and an IRepo in your BL without any notion of persistence, and leave the implementation details to InMemRepo or EFRepo in the DL. If you don't like IQueryable, return IEnumerable. Been doing it like this for years and switch DLs without *any* change to the BL. If your BL needs a ref to EF you know you're doing it wrong. – flip Dec 21 '16 at 00:26
  • rather technical question: what's the use of passing DbContext db to the repository class constructor here? Also, this kind of pattern feels pretty awkward if I have relationships between my ORM entities, as the interface `Save` method only takes my domain entity – emilaz Mar 10 '23 at 22:14
5

DbContext is indeed built with the Unit of Work pattern. It allows all of its entities to share the same context as we work with them. This implementation is internal to the DbContext.

However, it should be noted that if you instantiate two DbContext objects, neither of them will see the other's entities that they are each tracking. They are insulated from one another, which can be problematic.

When I build an MVC application, I want to ensure that during the course of the request, all my data access code works off of a single DbContext. To achieve that, I apply the Unit of Work as a pattern external to DbContext.

Here is my Unit of Work object from a barbecue recipe app I'm building:

public class UnitOfWork : IUnitOfWork
{
    private BarbecurianContext _context = new BarbecurianContext();
    private IRepository<Recipe> _recipeRepository;
    private IRepository<Category> _categoryRepository;
    private IRepository<Tag> _tagRepository;

    public IRepository<Recipe> RecipeRepository
    {
        get
        {
            if (_recipeRepository == null)
            {
                _recipeRepository = new RecipeRepository(_context);
            }
            return _recipeRepository;
        }
    }

    public void Save()
    {
        _context.SaveChanges();
    }
    **SNIP**

I attach all my repositories, which are all injected with the same DbContext, to my Unit of Work object. So long as any repositories are requested from the Unit of Work object, we can be assured that all our data access code will be managed with the same DbContext - awesome sauce!

If I were to use this in an MVC app, I would ensure the Unit of Work is used throughout the request by instantiating it in the controller, and using it throughout its actions:

public class RecipeController : Controller
{
    private IUnitOfWork _unitOfWork;
    private IRepository<Recipe> _recipeService;
    private IRepository<Category> _categoryService;
    private IRepository<Tag> _tagService;

    //Using Dependency Injection 
    public RecipeController(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
        _categoryRepository = _unitOfWork.CategoryRepository;
        _recipeRepository = _unitOfWork.RecipeRepository;
        _tagRepository = _unitOfWork.TagRepository;
    }

Now in our action, we can be assured that all our data access code will use the same DbContext:

    [HttpPost]
    public ActionResult Create(CreateEditRecipeViewModel model)
    {
        Mapper.CreateMap<CreateEditRecipeViewModel, Recipe>().ForMember(r => r.IngredientAmounts, opt => opt.Ignore());

        Recipe recipe = Mapper.Map<CreateEditRecipeViewModel, Recipe>(model);
        _recipeRepository.Create(recipe);
        foreach(Tag t in model.Tags){
             _tagRepository.Create(tag); //I'm using the same DbContext as the recipe repo!
        }
        _unitOfWork.Save();
Mister Epic
  • 16,295
  • 13
  • 76
  • 147
  • The DbContext of the Entity Framework is already an implementation of unit of work pattern. Why abstract an abstraction? – Pascal Jun 17 '14 at 20:57
  • Let's say your controller action needs to work with multiple repositories. If each of your repositories instantiates its own `DbContext`, you won't get transactional behaviour. By using the Unit of Work pattern in your controller, you can ensure that you pass the same instance to all of your repositories so that your operations will form part of the same transaction. Unit of Work isn't about abstraction, it is about ensuring that objects use the same context. – Mister Epic Jun 18 '14 at 11:48
  • I do not agree to this "By using the Unit of Work pattern in your controller, you can ensure that you pass the same instance to all of your repositories so that your operations will form part of the same transaction." The MyContext is injected into the Controller Per Api Request so every code within a controller action has access to the same MyContext. Let the IOC tool create the Context NOT the not needed IUnitOfWork implementation. There is no benefit. – Pascal Jun 18 '14 at 16:05
  • Microsoft has guidance on this very topic: http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application The OP was asking about the Unit of Work pattern, not IoC. You can certainly use IoC with lifetime management to accomplish the same thing, but Unit of Work is an enterprise design pattern that can be used to great effect: http://martinfowler.com/books/eaa.html If you wish, you can certainly submit another answer and propose another solution for the OP. – Mister Epic Jun 18 '14 at 16:17
  • 2
    How do you do unit tests? Each repository is DbContext based and I don't see how to inject a moq into that. Now, at the UoW level, you can change to another DbContext but it is still defined as a specific context. – Keith Barrows Sep 09 '14 at 20:43
  • 1
    @KeithBarrows In the words of someone more capable than I: "don't bother faking contexts" http://stackoverflow.com/questions/6904139/fake-dbcontext-of-entity-framework-4-1-to-test If you attempted to unit test with a fake for your context, you would be in the realm of Linq-To-Objects, not Linq-To-Entities. Your tests wouldn't be representative of what you would expect your production environment to be. The only way to really test code with EF is with integration tests. – Mister Epic Jan 19 '15 at 17:52
4

Searching around the internet I found this http://www.thereformedprogrammer.net/is-the-repository-pattern-useful-with-entity-framework/ it's a 2 part article about the usefulness of the repository pattern by Jon Smith. The second part focuses on a solution. Hope it helps!

Martin Blaustein
  • 1,063
  • 1
  • 8
  • 17
  • +1 for the link, it is really useful. I did follow the John Smith article to build our new project, and it is excellent. It is the way to go. Everyone should look at it if you are using EF. Accepted answer is outdated. – Dush Oct 03 '15 at 03:17
3

Repository with unit of work pattern implementation is a bad one to answer your question.

The DbContext of the entity framework is implemented by Microsoft according to the unit of work pattern. That means the context.SaveChanges is transactionally saving your changes in one go.

The DbSet is also an implementation of the Repository pattern. Do not build repositories that you can just do:

void Add(Customer c)
{
   _context.Customers.Add(c);
}

Create a one-liner method for what you can do inside the service anyway ???

There is no benefit and nobody is changing EF ORM to another ORM nowadays...

You do not need that freedom...

Chris Hardie is argumenting that there could be instantiated multiple context objects but already doing this you do it wrong...

Just use an IOC tool you like and setup the MyContext per Http Request and your are fine.

Take ninject for example:

kernel.Bind<ITeststepService>().To<TeststepService>().InRequestScope().WithConstructorArgument("context", c => new ITMSContext());

The service running the business logic gets the context injected.

Just keep it simple stupid :-)

Pascal
  • 12,265
  • 25
  • 103
  • 195
  • Your example is OK for a CRUD application where your Domain Object is the same as your Data Object. Repositories are Database ignorant. They only care about Business operations. – Pepito Fernandez Jul 15 '14 at 19:29
  • 2
    While most people tend to argue for separating data object from domain objects and always do the mapping (albeit automatic) I must agree with you Pascal. I have done so many mvc website projects using the n-tier design, repositories, services, etc. And you really don't need all that cumbersome logic. Now I've switched to using just 'Manager's or Service's which have the DBContext injected using Ninject from the controller and do their db operations. Works like a charm and provides more than enough freedom. I think the point here is that sometimes systems are so complex this no longer applies. – Peter Jan 23 '15 at 14:51
2

You should consider "command/query objects" as an alternative, you can find a bunch of interesting articles around this area, but here is a good one:

https://rob.conery.io/2014/03/03/repositories-and-unitofwork-are-not-a-good-idea/

When you need a transaction over multiple DB objects, use one command object per command to avoid the complexity of the UOW pattern.

A query object per query is likely unnecessary for most projects. Instead you might choose to start with a 'FooQueries' object ...by which I mean you can start with a Repository pattern for READS but name it as "Queries" to be explicit that it does not and should not do any inserts/updates.

Later, you might find splitting out individual query objects worthwhile if you want to add things like authorization and logging, you could feed a query object into a pipeline.

Darren
  • 9,014
  • 2
  • 39
  • 50
1

I always use UoW with EF code first. I find it more performant and easier tot manage your contexts, to prevent memory leaking and such. You can find an example of my workaround on my github: http://www.github.com/stefchri in the RADAR project.

If you have any questions about it feel free to ask them.

Gecko
  • 1,333
  • 1
  • 14
  • 26