I am struggling with solving how to handle insertions and deletions with MVC3 and the Entity Framework 4.2
My Setup:
Website accesses my Service Layer, which uses the Repository Pattern to fetch and return my Model(POCO) objects. The Solution is separated into the following projects:
DAL(Data)
BAL(Service layer in here)
MODELS (Poco objects)
WEBSITE (presentation)
My Problem:
I need to be able to control the adding and deletion of objects and run whatever business logic I like. This should be done in the Service Layer.
Example of Problem: I have an Account class with an ICollection of AccountContact objects. Each AccountContact object has an ICollection of PhoneNumber objects. What I envision is a Service method something like this
AddAcountContact(Account account, AccountContact accountContact){
//Run business logic to ensure that this account contact can be added
account.AccountContacts.Add(accountContact);
unitOfWork.SaveChanges();
}
DeleteAccountContact(Account account, AccountContact accountContact){
//Run business logic to ensure that this account contact can be deleted
account.AccountContacts.Remove(accountContact);
unitOfWork.SaveChanges();
}
Unfortunately I have no way to force adding and removing through my Service class. A developer could easily insert/remove directly from the presentation layer. Anyone have any ideas or know common solutions to this problem? Perhaps I am doing something wrong….
If you expose class with public collection property allowing
AddandRemoveyou are telling developers that they can call those methods. You can define the coding policy and use code review to check that policy is followed but it is only workaround. Still anybody could forget about that and callAddorRemovedirectly because your classes are wrongly designed.The main problem here are entities exposed directly to UI. If you don’t want direct modification of entities in UI layer simply don’t expose them to that layer. Use another type (DTO / View model) with readonly collections exchanged between service layer and UI layer and convert that type to entity inside service layer. Another option is adding validation directly to entities or custom collection types.