Reputation: 1270
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!
Upvotes: 3
Views: 7035
Reputation: 5168
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".
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.
Upvotes: 5