I wrote an article a while ago called Architecture of Business Layer working with Entity Framework, which has been popular. In that I used Eric Evans’ Domain- Driven Design (DDD) approach to building business logic with Entity Framework.

I am now playing with Entity Framework (EF) Core and some sample code made me think – could I better isolate the EF part of my Business Logic? The answer is yes, and this article describes the new and improved approach, with a lot more examples.

I have swapped to DDD-styled entity classes, which changes how my business logic is written. This is a big change to the original article. I decided to change this article rather than write a new one, as my new design replaces the previous design. I do describe the DDD-styled entity classes in this article, but see the article “Creating Domain-Driven Design entity classes with Entity Framework Core” , for a more detailed coverage of that topic.



I have also changed code to run that runs the business logic over to my open-source library, call GenericBizRunner. That makes takes away some of the hassle of running business logic.

People who have bought my book, “Entity Framework Core in Action” should note that I have updated chapter 10 to cover this approach to business logic. The update won’t be out until the book has finished its production cycle.

NOTE: You can apply the ideas in this article in EF6.x, but you can’t totally stop access to collection navigational properties in the same we you can in EF Core. This doesn’t stop you using this approach, it just means a developer can bypass the DDD style update if they really want to.

Domain-Driven Design and business logic

I am a big fan of Domain-Driven Design (DDD) and Eric Evans’ seminal book on DDD, Domain-Driven Design. Eric Evans’ book talks about how the business problem we are trying to solve, called the “Domain Model”, should be “the heart of the Software” (see Eric Evans book, page 4). Eric goes on to say “When the domain is complex, this is a difficult task, calling for the concentrated effort of talented ad skilled people”. Therefore, I try to make sure that the Business Logics data structures are defined by, and solely focused on, the business problem. How that data is stored and how that data is viewed are secondary issues.

What is Business Logic?

If you are new to idea of Business Logic, then I suggest you read the section near the top called ‘What is the Business Layer’ in my original article as it gives a good description. However, if you are in a hurry here is the short version.

Business Logic is what we call pieces of code that carry out operations that are specific to the job that the application is carrying out. For instance, on an e-commerce site like Amazon you would have Business Logic that handles a customer’s purchase: checking on availability and delivery, taking payments, sending an email confirmation etc. Business logic is definitely a step up on complexity over CRUD (Create, Read, Update and Delete) operations.

While Business Logic can be spread throughout an application and the database, it is accepted best practice to try and isolate the Business Logic. In my new, 2018 design I have some business logic in the entity classes, and some in a separate project/assembly, which am calling the Business Layer.

Aside: While having all the business rules in the Business Layer and entity classes is something we should always strive for I find that in practice some issues go outside these places for good reasons. For instance, validation of data often flows up to the Presentation Layer so that the user gets early feedback. It may also flow down to the database, which checks data written to the database, to ensure database integrity.

Other business logic appears in the Presentation Layer, like not allowing users to buy unless they provide a credit card, but the status should be controlled by the Business Layer. Part of the skill is to decide whether what you are doing is justifiable or will come back and bite you later! I often get that wrong, but hopefully I learn from my mistakes.

The (improved) architecture of my Business Layer

Let me start with a diagram of the new, improved structure of the Business Logic within an application – in this case an ASP.NET web application but the same approach would work in many other application types.

Next I will explain each of the main layers, with example code, by building some business logic that will process an order for some books that my example application “sells”.

NOTE: You can access the code used in this article, including a runnable example ASP.NET Core application which works, by cloning the GitHub repository GenericBizRunner. You need .NET Core installed, but example application uses an in-memory SQLite database, so you don’t need a database server installed (thanks to Henrik Blick for that suggestion).

The Data Layer is where the entity classes are defined, along with the EF setup and DbContext. In the new 2018 design the entity classes are written in a DDD-styled approach. For an in-depth look at my DDD pattern for entity classes see my article, Creating Domain-Driven Design entity classes with Entity Framework Core.

My DDD-styled entity classes contain business logic for creating and updating the entity class and any of its aggregates (aggregates is a DDD term that refer to entities that don’t make any sense outside a root entity – see the LineItem entity class in the example below).

My example is taking an order for some books. The order is held in a Order entity class, and the order has a one-to-many relationship to a LineItem entity class, which holds each item in the order. The code below shows you the DDD-styled Order class – the focus is on the Order’s static factory to create a properly constructed Order instance.

public class Order { private HashSet<LineItem> _lineItems; public int OrderId { get; private set; } public DateTime DateOrderedUtc { get; private set; } public DateTime ExpectedDeliveryDate { get; private set; } public bool HasBeenDelivered { get; private set; } public string CustomerName { get; private set; } // relationships public IEnumerable<LineItem> LineItems => _lineItems?.ToList(); public string OrderNumber => $"SO{OrderId:D6}"; private Order() { } public static IStatusGeneric<Order> CreateOrderFactory( string customerName, DateTime expectedDeliveryDate, IEnumerable<OrderBooksDto> bookOrders) { var status = new StatusGenericHandler<Order>(); var order = new Order { CustomerName = customerName, ExpectedDeliveryDate = expectedDeliveryDate, DateOrderedUtc = DateTime.UtcNow, HasBeenDelivered = expectedDeliveryDate < DateTime.Today }; byte lineNum = 1; order._lineItems = new HashSet<LineItem>(bookOrders .Select(x => new LineItem(x.numBooks, x.ChosenBook, lineNum++))); if (!order._lineItems.Any()) status.AddError("No items in your basket."); status.Result = order; return status; } //... other access methods left out }

Things to note from this code are:

Lines 3 to 7. Note that all the properties have private setters. That means that the developer has to go through the public constructor or any access methods to change anything in the entity (see this link about the DDD-sytled entity and access methods).

Line 9,10: The one-to-many list of LineItems is implemented as a EF Core backing field. This means the navigational collection is held in a private field, and the developer can only read it as an IEnumerbale<LineItem> property, which means they cannot add, remove or clear the collection. This means only the Order entity class can alter this collection.

Line 17: EF Core needs a parameterless constructor so that it can create instances of the entity class when it reads in data. But I can make that a private constuctor, which means a developer outside this class cannot create a default (i.e. empty, and therefore invalid) instance.

Lines 19 to 21: Because the creation of the Order might include a business rule error, which is fixable by the user, then I use a static factory method for creating the Order. This means I can return a result of type of IStatusGeneric<Order>, which a status and, if no errors, the created Order instance. If there were no possibilities of fixeable errors I would have used a public constructor with parameters.

Lines 32 to 34: This builds a list of LineItem entities. The LineItem entity class has an internal access constructor which creates a valid LineItem. Because the LineItem is a aggregate of the Order class, then only the Order should create/change the LineItems.

2. The BizLogic Layer

I have written numerous applications, all of which has some quite complex Business Logic. Over the years I have tried different ways of organising these applications and I have come up with one key philosophy – that the “The Business Logic is King“, i.e. its design and needs drives everything else.

My rules for the Business Logic are:

a. The Business Logic data classes should not be affected by other higher layers

Business Logic can be hard to write. Therefore, I want to stay focused on business issue and not worry about how other layers above might need to reformat/adapt it. So, all data in or out of the Business Logic is either defined inside the BizLogic layer, or it is a Data Layer class. It is Service Layer’s job to act as an Adapter, i.e. Service Layer converts any data to/from what the Business Logic needs.

In new/modern databases the entity classes should be a very good fit to the Business Logic needs, with a few extra properties needed to set up the database relationships, e.g. Foreign Keys. Therefore, the Business Logic can use the EF entity classes directly without any adaption.

However, one of my reader, , pointed out that for for old/legacy databases the fit between what the database and what the Business Logic may not be a good match.

b. The Business Logic works on a set of in-memory data

I don’t want the Business Logic worrying about how to load and save data in the database. It is much simpler to design the Business Logic code to work on simple in-memory set of data. The changes described in this article improve this significantly over the previous article.

In the previous approach I used to have a specific part of the Business Logic, normally at the start, which loaded all of the data. However, the new approach has what I call a DbAccess class which handles all the reading and writing (see later for why this is better). The DbAccess is class is a Facade pattern.

Example Code

Here is an example of Business Logic which is creating the Order. It is fairly simple, beacause the Order.CreateOrderFactory does quite a bit of it, with the PlaceOrderAction and the PlaceOrderDbAccess (see later) finding the Book entities.

public interface IPlaceOrderAction : IGenericActionWriteDb<PlaceOrderInDto, Order> { } public class PlaceOrderAction : BizActionStatus, IPlaceOrderAction { private readonly IPlaceOrderDbAccess _dbAccess; public PlaceOrderAction(IPlaceOrderDbAccess dbAccess) { _dbAccess = dbAccess; } public Order BizAction(PlaceOrderInDto dto) { if (!dto.AcceptTAndCs) { AddError("You must accept the T&Cs to place an order."); return null; } var bookOrders = dto.CheckoutLineItems.Select( x => _dbAccess.BuildBooksDto(x.BookId, x.NumBooks)); var orderStatus = Order.CreateOrderFactory( dto.UserId, DateTime.Today.AddDays(5), bookOrders); CombineErrors(orderStatus); if (!HasErrors) _dbAccess.Add(orderStatus.Result); return HasErrors ? null : orderStatus.Result; } }

A few things to point out about the above.

Line 1 and 2: The IPlaceOrderAction interface uses a GeneriBizRunner interface that tells the BizRunner that it has an input (PlaceOrderInDto), an output (Order) and that SaveChanges should be called if the method finishes without errors.

The IPlaceOrderAction interface uses a GeneriBizRunner interface that tells the BizRunner that it has an input (PlaceOrderInDto), an output (Order) and that SaveChanges should be called if the method finishes without errors. Line 4: The PlaceOrderAction class inherits the BizActionStatus class, which is provided by the GenericBizRunner. This provides error handling, with methods such as AddError and a list of Errors. This is communcated back to the caller via the GeneriBizRunner service instance.

The PlaceOrderAction class inherits the BizActionStatus class, which is provided by the GenericBizRunner. This provides error handling, with methods such as AddError and a list of Errors. This is communcated back to the caller via the GeneriBizRunner service instance. Lines 6 to 11: The PlaceOrderAction class uses a class that implements the IPlaceOrderDbAccess interface. This is provided via dependency injection.

The PlaceOrderAction class uses a class that implements the IPlaceOrderDbAccess interface. This is provided via dependency injection. Lines 23 and 30: The IPlaceOrderDbAccess class contains a methods that the bsuiness logic can use to a) find the books the customer wants and b) adds the new order to the database.

This design splits the load between this class in the Business Layer and the Order entity class. In my design I deem that an entity class can work on itself (called the root entity) and any of its aggregates, i.e. navigational links that it the root entity handles. This means that the Order entity class doesn’t handle any Book accesses, which is why that is done in this PlaceOrderAction class.

2. The BizDbAccess Layer (new 2016)

The BizDbAccess layer contains a corresponding class for each BizLogic class that accesses the database. It is a very thin Facade over the EF calls. I should stress, I am not trying to hide the EF calls, or make a repository. I am just trying to Isolate the calls. Let me explain.

The problem with my previous approach, where the Business Logic called EF directly, wasn’t that it didn’t work, but that it was hard to remember where all the EF calls were. When it came to refactoring, especially when doing performance improvements, then I had to hunt around to check I had got every EF call. By simply moving all the EF calls into another class I have all of the EF commands in one place.

The main approach I will describe assumes that the database is of a new/modern design and there is a good fit between the data held in the database and the Business Logic requirements. The code below is a PlaceOrderDbAccess class, which goes with the PlaceOrderAction Business Logic described above:

public class PlaceOrderDbAccess : IPlaceOrderDbAccess { private readonly EfCoreContext _context; public PlaceOrderDbAccess(EfCoreContext context) { _context = context; } public OrderBooksDto BuildBooksDto(int bookId, byte numBooks) { return new OrderBooksDto(bookId, _context.Find<Book>(bookId), numBooks); } public void Add(Order newOrder) { _context.Orders.Add(newOrder); } }

Please note that I use a method called Add, to add the order to the EF Orders DbSet. As I said, I am not trying to hide what is going on, but just isolate the commands, so using the same terminology is helpful.

NOTE: To help with finding the relevant DbAccess I call the Business Logic class <name>Action and the DbAccess calls <name>DbAccess. They also have the same top-level directory name. See the attached picture of the solution directories on the right.

NOTE: When it comes to unit testing business logic it can be useful to be able to mock the BizDbAccess methods, especially for complex business logic where you want to force errors. For more simple business logic I find EF Core’s in-memory databases make unit testing quite easy. See my article “Using in-memory databases for unit testing EF Core applications” for more on that.

Handling old/legacy databases

One of my readers, , has been using a similar approach to the one describe in this article for some time. He pointed out in one of his comments that he finds this approach useful when the database tables are not a good fit for the Business Logic.

At that point, in addition to isolating the EF commands, the BizDbAccess class can carry out any adapting/ reformatting of the data between the database and the Business Logic.

For example, I have come across database which does not mark its relationship keys and Foreign Keys. This stops EF from doing relational fixup, i.e. linking the various entities loaded. In that case you would add code to the DbAccess class to link the loaded entities so that the Business Logic can work on a linked, in-memory set of classes.

The Service Layer

As I said earlier in my applications the Service Layer is very important layer that links everything together. The Service Layer provides a Command pattern and the Adapter pattern between the presentation layer and all the layers below.

Note: You can read more about my thoughts on the business layer in the Service Layer part of my “Six ways to build better Entity Framework (Core and EF6) applications” article.

In this case I have abstracted all the code, other than any DTOs (Data Tranfer Objects – simple classes to pass data around), into my library GenericBizRunner. This provides both the contains the Command pattern and the Adapter patterns.

Adapter pattern : The GenericBizRunner can handle UI-centric DTOs, with things like dropdownlists etc, and then map just the data that the business logic needs to do its job. That insulates the business logic from any need to think about, or deal with, UI data.

: The GenericBizRunner can handle UI-centric DTOs, with things like dropdownlists etc, and then map just the data that the business logic needs to do its job. That insulates the business logic from any need to think about, or deal with, UI data. Command pattern: It is the job the the GenericBizRunner to run the business logic and call SaveChanges (with data validation if required) if the business logic was successful. It also passes back the status of the whole process (biz logic status and any validation errors from SaveChangesWithValidation) to the front-end system.

Note: The discarding of data by not calling ‘SaveChanges’ only works in situation where each call has its own DbContext. This is the case in a web application as each HTTP request gets a new DbContext. However, in Windows Applications etc. where the DbContext can be kept alive for longer you need to be careful about the lifetime/disposal of the DbContext.

The GenericBizRunner saves you from writing the code to run and check the business logic. You can find out more about the library in my article “A library to run your business logic when using Entity Framework Core“. In the next section you will see how I call the business logic via the GenericBizRunner.

Presentation layer/API

At the top level you want to run your business logic. That could be in a human-focused screen or an API talking to another system – it doesn’t really matter. The point is your business logic should be isolated from the front-end. But at the same time the front-end may need features/requirements to make the application to work in its environment, like showing the user what is in their e-commerce basket.

In my example case I am using an ASP.NET Core application for my example, showing HTML pages via razor. I have used a cookie to hold the customers basket, and when the order is successfully placed I need to clear that cookie. Also, I want to show a confirmation page showing that the order was successfully placed, and when it might arrive.

In this case I have handled the cookie side of things inside the ASP.NET Core action method. I try to keep the ASP.NET Core action methods to have a standard format, but in this case the cookie part meant I needed some more code. NOTE: If I had put the basket in the database then the PlaceOrderAction could have cleared the basket as part of the business logic.

[HttpPost] [ValidateAntiForgeryToken] public IActionResult PlaceOrder(PlaceOrderInDto dto, [FromServices]IActionService<IPlaceOrderAction> service) { if (!ModelState.IsValid) { return View("Index", FormCheckoutDtoFromCookie(HttpContext)); } var order = service.RunBizAction<Order>(dto); if (!service.Status.HasErrors) { ClearCheckoutCookie(HttpContext); return RedirectToAction("ConfirmOrder", "Orders", new { order.OrderId, Message = "Your order is confirmed" }); } //Otherwise errors, so I need to redisplay the basket from the cookie var checkoutDto = FormCheckoutDtoFromCookie(HttpContext); service.Status.CopyErrorsToModelState(ModelState, checkoutDto); return View("Index", checkoutDto); }

The parts of the code I want to point out are:

Line 4. I am a great fan of dependency injection (DI) and ASP.NET Core provides a way to inject something into the parameters of an action method. The IActionService<IPlaceOrderAction> returns an instance of the GenericBizRunner, which in turn has an instance of the PlaceOrderAction class (again via DI). This makes accessing the BizRunner with its business logic very easy (and it works in razor pages too).

Lines 11 to 18: The BizRunner instance runs the business logic. In this case the business takes an input (PlaceOrderInDto) and returns a result (Order). On success my code has to clear the cookie and redirects to the ConfirmOrder action to show the successful order details.

Lines 21 to 23: When there are errors we want to redislay the customer’s basket, and show what was wrong. The CopyErrorsToModelState extension method is one I have written that will converts the GenericBizRunner’s IStatusGeneric errors into ModelState errors to show to the customer.

Quick aside – handling errors needs thought.

This article is already quite long, so I won’t dwell on this subject, but providing good error feedback to the user is not trivial. Many libraries use Exceptions to report errors – some of these errors are user friendly, like Validation Errors. However, many Exceptions, such as EF’s DbUpdateException, are very unfriendly and sometimes produce messages that relate to the inner working for the application, and hence should not be shown for security reasons.

The GenericBizRunner library have implemented a status feedback mechanisum, and I am in the process of extending it to other uses (you already saw the IStatusGeneric<T> return on the Order’s static CreateOrderFactory, which includes a return value too). The main point on on errors that the user/system can correct is to return all the errors in one go, especially in human-facing system. That way the user won’t get frustrated by having to fixed each error before another error is shown.

Conclusion

I recently reviewed an e-commerce application I developed which used the older approach to writing Business Logic, i.e. EF called in the Business Logic. The Business Logic was quite complex, especially around pricing and delivery. My conclusion was that the Business Logic work fine, but it was sometimes difficult to find and understand the database accesses when refactoring and performance tuning the Business Logic.

I tried out the new approach described in this article by refactoring some of the Business Logic in this e-commerce application over to the new approach. Overall it did make a difference by bring all the EF access code into one clear group per Business Logic case.

In additions I have been working with EF Core for over a year, and I have (finally) found a pattern for DDD-styled entity classes. I think this improved the business logic again, with even better separation of concerns (and for CRUD access too – see my article on DDD-styled entities).

The only down side to this new approach is that does need one more class than the previous approach. However, that class does provide a much better separation of concerns. Therefore, I think this new approach is a positive improvement to my previous approach to building Business Logic and is worth the effort extra effort of another class.

I hope this article gives you some ideas on how to better design and build complex Business Logic in your applications.