2
votes

I am quite new to Entity Framework, and still struggling to solve it.So many different examples and explanations that i can't figure out what to do ?

I have a few questions :

In my current application I used a pattern which consist of :

  • Repository Pattern
  • (On top of )Unit Of Work

For each from , I am declaring a NEW Unit Of Work .So when I make a Savechanges, only the related items are affected.

For complex business logics , I am writing my methods inside the Repository for each class For example :

  • One method for : Remove one item from one inventory location , move it to another location and then decrease the quantity at the old location, etc... -Or much more complex jobs, which reads from different tables and write to many tables.

However recently I found out that by Entity Framework 6.0 :

  1. DbContext = Unit Of Work
  2. DbSet is equivalent to REPOSITORY

So the questions are :

  1. Should i use ONE DBCONTEXT ,or declare a new for each form/operation so the transactions remain in the local context ( form/operation =
    1. How will I replace the methods in my the repository ?

Thanks

1
DbSet is NOT a repository, unless your Domain objects can be used 'as is' by the EF. Even then, the fact that it exposes IQueryable defeats the purpose of the Repository pattern. In a nutshell, the Repository is a principle and its implementation is not DbSet, but the implementation can use EF as an internal detail.MikeSW
thanks, that was the point I was mistaken, sorry for showing the correct path.Vedat Galimidi

1 Answers

2
votes

First of all trying to treat your DbContext as singleton object is a bad idea, because you can't manage transactions in your operations. you have to instantiate your DbContext per operation.

Second, try to separate your "Data layer concerns" from your "Business concerns". for example :

One method for : Remove one item from one inventory location , move it to another location and then decrease the quantity at the old location

I think you are writing your repository methods per use case which is not a data layer concern. your repositories are only need to know about persisting and retrieving objects. in another way your repository methods are just CRUD methods. Your business layer will use this methods to perform business logic.