简体   繁体   中英

Business layer design - How to define rules

I understand that its a best practice to put your business rules in a business layer and your data access in a separate data access layer, while the entities are part of your model.

So for example i'm working with a Customer entity defined in my model, i can fetch all customers from the database via the Data access layer. I can also add a new customer, via the DAL.

However before I add the customer, i need to run a validation on it - so i guess i need to define the rules in the business layer - but i'm not quite sure how to go about it.

Does my business layer only have methods which accept the entities as parameters? Something like BLL.Customers.Validate(Model.Customer customer) ?

Or

Does my business layer extend my Entities? Should I make the entity classes like Customer partial classes? so that the BLL can extend them further with business rules?

I'm not sure how to design the business layer.

Your entities should really carry all their own business behaviour, so there would be a Validate method on the entity itself. I also like to have a static factory method in my entities for creating an entity:

public class Cusotmer
{
    private long? _id;
    private string _name;
    //other attributes...

    public static Customer Create(string name)
    {
        Customer customer = new Customer();
    }

    public void Validate()
    {
        if(_name == null)
            throw new ValidationException("Name has not been set.");
    }
}

I'm not sure why you need partial classes, except maybe if you're code generating your entities from a database perhaps?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM