Reputation: 1742
I'm confused about one thing. I've used a repository pattern (not generic) in my previous mvc apps and I used to include some kind of business logic there. At this moment I read about service layer pattern where should be included BL. But now I don't know if there is more abstraction and extra code instead of cleary/readable and efficient code.
I want to implement a method like this
public void ChangeActiveField(bool isActive, int id)
{
var objectToUpdate = _context.FirstOrDefault(x=>x.id==id);
objectToUpdate.IsActive - isActive;
_context.Entry(objectToUpdate).State = System.Data.Entity.EntityState.Modified;
_context.Save();
}
In this code there is a bit of business logic where I change state of one field and after that I update this. Should I make it in service layer and then use simple repository update method liek this: ?
public class MyService
{
private readonly IMyRepository = _myRepo;
MyService(IMyRepository myRepo) //it's injectable
{
_myRepo = myRepo;
}
public void ChangeActiveField(bool isActive, int id)
{
var myObject = _myRepo.GetMyObject(id);
myObject.IsActive = isActive;
_myRepo.Update(myObject);
}
}
Is it better aproach? Does it make better separation? Or it's too sophisticated and overwrite? Thank you for your help. Best regards.
Upvotes: 2
Views: 630
Reputation: 8781
In general repository should encapsulate only the logic of accessing database (initialization of context, transactions, connections and etc.). It is very common to create a generic CRUD repository and reuse it for all your business entities. All the business related logic should be placed in business layer(service layer). The major benefits of this approach are:
In my experience having a business layer (no matter how simple it is at the beginning - it's often grows up together with your project) is always a good idea.
By the way some developers consider repository as an unnecessary layer of abstraction in case that you use EF (in a way EF database context is a repository...).
One thing I've learned, is that the major effort is not a development phase of a project it is it's maintenance and upgrades - and here having a business layer a significant impact.
Disclaimer: It is my subjective opinion based on my experience
Upvotes: 1