concept business logic in category entity framework

appears as: business logic, business logic, The business logic
Entity Framework Core in Action, SE

This is an excerpt from Manning's book Entity Framework Core in Action, SE.

I had applied good software practices and made sure the database and business logic were matched to the problem space—that of modeling and optimizing the location of health facilities. That was fine, but I spent an inordinate amount of time writing code to convert the database entries and business logic into a form suitable to show to the user. Also, I was using a Repository/Unit of Work pattern to hide EF5 code, and I was continually having to tweak areas to make the repository work properly.

The code you write to implement a business rule is known as business logic or domain logic. Because business rules can be complex, the business logic you write can also be complex. Just think about all the checks and steps that should be done when you order something online.

Business logic can range from a simple check of status to massive artificial intelligence (AI) code, but in nearly all cases, business logic needs access to a database. Although the approaches in chapters 2 and 3 all come into play, the way you apply those EF Core commands in business logic can be a little different, which is why I’ve written this chapter.

This chapter describes a pattern for handling business logic that compartmentalizes some of the complexity in order to reduce the load on you, the developer. You’ll also learn several techniques for writing different types business logic that uses EF Core to access the database. These techniques range from using software classes for validation to standardizing your business logic’s interface in order to make frontend code simpler. The overall aim is to help you quickly write accurate, understandable, and well-performing business logic.

Figure 4.1 The checkout page of the Book App. When the user clicks the “Buy Book” button next to a book it adds the book to their basket and then goes to the Checkout page where it displays all the books in the user’s basket. Clicking the “Purchase” button calls the business logic to create the order, which is the code we are going to write.

4.4.5 Guideline 5: Business logic shouldn’t call EF Core’s SaveChanges

The final rule says that the business logic doesn’t call EF Core’s SaveChanges, which would update the database directly. There are a few reasons for this. First, you consider the service layer as the main orchestrator of database accesses: it’s in command of what gets written to the database. Second, the service layer calls SaveChanges only if the business logic returns no errors.

To help you run your business logic, I’ve built a series of simple classes that I use to run any business logic; I call these BizRunners. They’re generic classes, able to run business logic with different input and output types. Different variants of the BizRunner can handle different input/output combinations and async methods (chapter 5 covers async/await with EF Core), plus some with extra features, which are PlaceOrderAction covered later in this chapter.

Each BizRunner works by defining a generic interface that the business logic must implement. Your class in the BizLogic project runs an action that expects a single input parameter of type PlaceOrderInDto and returns an object of type Order. Therefore, the PlaceOrderAction class implements the interface as shown in the following listing, but with its input and output types (IBizAction<PlaceOrderInDto,Order>).

Listing 4.4 The interface that allows the BizRunner to execute business logic
public interface IBizAction<in TIn, out TOut>  #A
{
    IImmutableList<ValidationResult>         #B
        Errors { get; }                      #B
    bool HasErrors { get; }                  #B
    TOut Action(TIn dto);                    #C
}
Entity Framework Core in Action

This is an excerpt from Manning's book Entity Framework Core in Action.

  • Using EF Core in business logic
  • The code you write to implement a business rule is known as business logic or domain logic. Because business rules can be complex, the business logic you write can also be complex. Just think about all the checks and steps that should be done when you order something online.

    Business logic can range from a simple check of status to massive artificial intelligence (AI) code, but in nearly all cases, business logic needs access to a database. Although the approaches in chapters 2 and 3 all come into play, the way you apply those EF Core commands in business logic can be a little different, which is why I’ve written this chapter.

    This chapter describes a pattern for handling business logic that compartmentalizes some of the complexity in order to reduce the load on you, the developer. You’ll also learn several techniques for writing business logic that uses EF Core to access the database. These techniques range from using software classes for validation to standardizing your business logic’s interface in order to make frontend code simpler. The overall aim is to help you quickly write accurate, understandable, and well-performing business logic.

    Figure 4.1 The checkout page of the book app. Clicking Purchase calls the business logic to create the order.

    04-01.png
    Listing 4.1 Abstract base class providing error handling for your business logic
    public abstract class BizActionErrors    #1  
    {
        private readonly List<ValidationResult> _errors    #2  
            = new List<ValidationResult>();    #2  
        public IImmutableList<ValidationResult>    #3  
            Errors => _errors.ToImmutableList();  #3  
        public bool HasErrors => _errors.Any();    #4  
        protected void AddError(string errorMessage,    #5  
            params string[] propertyNames)    #5  
        {
            _errors.Add( new ValidationResult    #6  
                (errorMessage, propertyNames));  #6  
        }
    }
    
    #1   Abstract class that provides error handling for business logic
    #2   Holds the list of validation errors privately
    #3   Provides a public, immutable list of errors
    #4   Creates a bool HasErrors to make checking for errors easier
    #5   Allows a simple error message, or an error message with properties linked to it, to be added to the errors list.
    #6   Validation result has an error message and a possibly empty list of properties it’s linked to.