My basic solution structure in every project is:
- Dal – Data access layer
- Business logic which divided into two sections one is business entities and the second is business logic
So in my current practice my entities includes only data members and properties and NOT CRUD operations.
It’s always felt wrong to put CRUD operations within the Entity. My thought was..
- It’s OK which entity deletes himself?
- It’s OK which entity adds
himself to the DB?
So i moved the CRUD operation to another library (Class) which represent my business Logic.
For example let say that we have an foo entity
public class Foo
{
//Data Members
private int _id;
private string _Name;
//Properties
public int ID { get; set; }
public string Name { get; set; }
}
So for this entity i will create a FooLogic library (Class) which holds all CRUD operations Like:
- Add a New Entity
- Delete an Entity
- Get a list of entities
- Update an entity
And so on..
So what i am asking is:
- It’s right practice not to put the CRUD operations within the entity object?
- If so, What methods should i put in the entity himself of course beside “Print details”
- It’s Ok to have business Logic library (Class) for each important entity?
I can’t speak for what is absolutely correct in every circumstance (because nothing is, but also because I’m not a true “enterprise”-y developer), but…
DbContextis a repository already. You do not need to reimplement the Repository pattern yourself.Person.GetFullName()which would concatenate thePerson.FirstNameandPerson.LastNamefields, for example.Personclass calledSendEmailTo()because that is not really an operation on the Person, but on your e-mail system.Here’s how I’d implement a simple CRM (with a single entity, the
Customer):An entity class
DBCustomer:(presumably generated by Entity Framework) that represents a customer stored in the database.
A repository
The Entity Framework
DbContextis your repository object so no work needs to be done here.Business logic
…such as a WCF message handler – but sometimes the logic is really simple, especially when the business action corresponds directly to a database action, e.g.
Now you might notice that there seems to be a lot of useless layers here – I could use the CustomerXml class (which represents a deserialized formerly-XML-formatted message) and then call the EF context methods directly from the WCF message event handler, and it would would work for very trivial projects, however as projects grow you’ll see you need to add custom logic at every step, and suddenly things get unmanageable quickly.
So for a simple data-driven website then a simple “do everything in the ame layer” approach would work fine, but an “entperprise” application with lots of niggles in the specification is going to need these extra layers.