3

I am new to Entity Framework and .NET and am working on building an MVC 4 application. I think I'm a little confused about where my database context instances should be created. In my application, I have several layers: Web, Business, Data Access, Database (these are each separate projects). In the data access layer, I have one class per table. An example I saw shows creating the context inside each method inside the data access layer (I may have misunderstood it). This doesn't seem very practical when updating multiple tables as part of the business logic. It seems the result of creating a new context inside each data access layer method is this error: An entity object cannot be referenced by multiple instances of IEntityChangeTracker when updating multiple tables.

So is it acceptable to create the context in the business layer method and then pass that to the data access layer methods? Or is there a better way to do it?

Something like this where the context comes from the business layer:

public User RetrieveUserById(int id, MyDbContext ctx)
    {            
        User findUser = ctx.Users.Find(id);
        return findUser;
    }

instead of creating the context inside the data access layer method:

public User RetrieveUserById(int id)
    {
        var ctx = new MyDbContext();
        User findUser = ctx.Users.Find(id);
        return findUser;
    }

I appreciate the help!

ssn771
  • 1,270
  • 2
  • 17
  • 20
  • I see what you are saying. I just created a separate project with classes for doing CRUD operations on the entities generated by EF. So EF generated one class per table, then I created one class per table for performing the CRUD operations. Is that not a good idea? – ssn771 Mar 27 '13 at 22:54
  • With how you are describing your methods, this is more of a reposity pattern. The orm takes care of the dal and mapper. – Justin Mar 27 '13 at 23:12

1 Answers1

5

Data access layer. Create a "Unit of work" class which exists in the data layer together with the DbContext. Try searching for "Asp.net unit of work pattern".

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-application1

Basically, it is a central place to bring together multiple repositories/tables, so that you can act on multiple repositories without disposing your context. You don't have to use it exactly as shown. You can modify it to fit your needs.

sunil
  • 5,078
  • 6
  • 28
  • 33