Loading...
Area: Episerver B2B Commerce

Working with the data model and Entity Framework ORM

Recommended reading 

Episerver used Entity Framework for Epi B2B Commerce. Let's look at a variety of topics to help you acclimate to the new data layer:

  • Goals and Best Practices
  • Basic Usage
  • Extensibility
  • Performance

Goals and Best Practices

The goals of the Epi B2B Commerce data layer are:

  1. Use the Entity Framework.
  2. Encourage a "thin" data layer, or a data layer whose entities have little to no business logic.

Entity Framework

Entity Framework (EF) is open source and part of the .NET framwork. EF is the default object relational mapper (ORM) for Epi B2B Commerce. This type of tool simplifies mapping between objects in software to the tables and columns of a relational database.

Skinny Data Model

We want to host all business logic in the service layer, leaving the entities as simple as possible. This eliminates complexity in the data layer and allows for better control and extensibility throughout the platform. We encourage you to follow this paradigm as you extend the platform.

Insite.Data

The Insite.Data namespace is the root namespace for entity-related components in the Epi B2B Commerce framework. The models are Insite.Data.Entities and many other data-related components are included this namespace. Insite.Data is the main dependency for all data layer-related logic.

Basic Usage

Unit of Work and Repositories

The recommended way to access data is to obtain a UnitOfWork object, get the appropriate Repository<T> object, and use that repository to access the entities.

Retrieving Entities

To get an entity by Id, get the object by its primary key by calling the Get method on the corresponding repository.

Getting a List of Entities

To retrieve a list of entities, call the GetTable method, which returns an IQueryable<T> that can be filtered (where), sorted (orderby) or mapped (select).

Also, if you would rather write your own optimized SQL for retrieving the entities, you can do so and call GetList.

NOTE: This will return the values immediately. This method should be used with care and only when necessary.

Retrieving Related Data

Lazy Loading

By default, lazy loading is enabled and can be used to retrieve entities and collections of entities related to your entity in the database. A separate SQL call will be made once the collection is accessed in the code to retrieve these entities. In the example below, there are two SQL calls made, one for the Get and one when Job.CustomProperties is accessed.

Eager Loading

Although lazy loading is great for a number of use cases, it is sometimes advantageous to load collections ahead of time if you know that you are planning to access them. This optimizes the process by making only one SQL call.

In our last example, we always access the CustomProperties collection, so instead of lazy loading that collection, we can eagerly load it via the Expand method provided by Insite.Data.Extensions.

NOTE: You must return an IQueryable to use this method.

Updating Entities

Creating an Entity

Creating an entity consists of constructing a new instance of the desired entity type, and calling the Insert method on the corresponding repository.

NOTE: To actually save the entity to the database, you will also need to call either the Save or SaveAsync method on the UnitOfWork. That will be covered in the next SubTopic.

Updating an Entity

Updating an attached entity requires an update to the instance, followed by a call to the Save method on the UnitOfWork instance.

You can also perform a Save asynchronously by calling SaveAsync on the UnitOfWork instance.

NOTE: You do not have to call Save or SaveAsync immediately after updating the entity

Deleting an Entity

Deleting a job requires you invoke the Delete method on the Repository, followed by Save or SaveAsync on the UnitOfWork.

NOTE: You do not have to call Save or SaveAsync immediately after updating the entity

Extending the Data Model

Altering the Data Model

The officially supported best practice and method for changing the data model is to add entities to the model. Removing Episerver tables is not supported. See Creating Custom Tables with an Entity and WebApi for details about table extension.

Creating an Entity Class

Getting Started

To add to the data model, you should first create a POCO (Plain Old CLR Object) that extends from Insite.Data.Entities.EntityBase. For this example we have created the Job class.

Convention and Annotations

In the previous image, you'll notice that a Table attribute/annotation was added to this class. This is superfluous as convention assumes the name of the class. A list of common annotations for EF can be found here

https://msdn.microsoft.com/en-us/data/jj591583.aspx

Adding Properties

Once your class is created, you can begin to add properties. Properties can be of varying types, including other entities, but must have "virtual" as part of their signatures. Keeping in mind the principle of a "thin" data layer, it is best practice to leave out computed properties or methods. Our example adds the following:

Mapping the Entity

Getting Started

Once you have created your entity class, you must create a mapping class. This class defines any custom relationships that are outside of standard entity framework conventions. Since our example follows convention, we don't require any logic. Still, we need to create the class, and it must extend from Insite.Data.Providers.EntityFramework.EntityMappings.EntityBaseTypeConfiguration<T> in order for your entity to be bootstrapped to the context correctly.

Custom Mappings

Primarily, you will only need to add custom mapping logic to your mapping class if there is a many-to-many relationship between your entity and another. If this is the case, then you can follow standard entity framework guidance on creating this mapping.

Altering the Database Schema

Migrations

Migrations are not currently supported. Any changes made to the database schema need to be done via SQL files embedded in your custom dll's.

Creating a Script

Creating a script consists of adding a new SQL file to your Visual Studio Project. The file should have the format of <year>.<month>.<day>.<increment>.<description>.sql. These can be added anywhere in the project's folder structure.

Including a Script

Including a script into the build consists of setting the Build Action property of the file to Embedded Resource and the Copy to Output Directory property to Do not copy.

Running a SQL Script

SQL scripts that are embedded resources are run automatically during the bootstrap operation. If the SQL script executes successfully, it is added to the DatabaseScript table in the database. This is done for auditing purposes, and to ensure that a script is not run twice. You can query this table to determine if your script has been run.

Performance Considerations

Retrieving Records

WhereContains

There is a known issue using Linq with Entity Framework in conjunction with ICollection<T>.Contains() from within a Where clause. An example of this would be as follows:

Using this approach can severely degrade the performance of your application. To alleviate this issue, Episerver has provided an extension method, WhereContains, which gives the same result in a much more performant manner. The same method as above should be refactored to the following:

WithNoTracking

Another optimization that can be made is to work with a set of data that doesn't have change tracking enabled. This improves read performance, and can also improve the performance for batch operations.

Entity Framework accomplishes this via the AsNoTracking extension method, found here

https://msdn.microsoft.com/en-us/library/gg679352(v=vs.103).aspx

To limit dependencies on Entity Framework, Episerver Commerce exposes the same functionality on all of their repository instances. To get a collection without tracking, invoke the GetTableAsNoTracking method on the Repository. An example would look like the following:

Typical usage would be scenarios where no updates to the entity are expected, or optimized sections where ObjectState and attachment to the context will be actively managed.

Do you find this information helpful? Please log in to provide feedback.

Last updated: Dec 11, 2020

Recommended reading