Entity Framework Core Integration

This document explains how to integrate EF Core as an ORM provider to ABP based applications and how to configure it.

Installation

Volo.Abp.EntityFrameworkCore is the main nuget package for the EF Core integration. Install it to your project (for a layered application, to your data/infrastructure layer):

  1. Install-Package Volo.Abp.EntityFrameworkCore

Then add AbpEntityFrameworkCoreModule module dependency (DependsOn attribute) to your module:

  1. using Volo.Abp.EntityFrameworkCore;
  2. using Volo.Abp.Modularity;
  3. namespace MyCompany.MyProject
  4. {
  5. [DependsOn(typeof(AbpEntityFrameworkCoreModule))]
  6. public class MyModule : AbpModule
  7. {
  8. //...
  9. }
  10. }

Note: Instead, you can directly download a startup template with EF Core pre-installed.

Database Management System Selection

Entity Framework Core supports various database management systems (see all). ABP framework and this document doesn’t depend on any specific DBMS.

If you are creating a reusable application module, avoid to depend on a specific DBMS package. However, in a final application you eventually will select a DBMS.

See Switch to Another DBMS for Entity Framework Core document to learn how to switch the DBMS.

Creating DbContext

You can create your DbContext as you normally do. It should be derived from AbpDbContext<T> as shown below:

  1. using Microsoft.EntityFrameworkCore;
  2. using Volo.Abp.EntityFrameworkCore;
  3. namespace MyCompany.MyProject
  4. {
  5. public class MyDbContext : AbpDbContext<MyDbContext>
  6. {
  7. //...your DbSet properties here
  8. public MyDbContext(DbContextOptions<MyDbContext> options)
  9. : base(options)
  10. {
  11. }
  12. }
  13. }

About the EF Core Fluent Mapping

The application startup template has been configured to use the EF Core fluent configuration API to map your entities to your database tables.

You can still use the data annotation attributes (like [Required]) on the properties of your entity while the ABP documentation generally follows the fluent mapping API approach. It is up to you.

ABP Framework has some base entity classes and conventions (see the entities document) and it provides some useful extension methods to configure the properties inherited from the base entity classes.

ConfigureByConvention Method

ConfigureByConvention() is the main extension method that configures all the base properties and conventions for your entities. So, it is a best practice to call this method for all your entities, in your fluent mapping code.

Example: Assume that you’ve a Book entity derived from AggregateRoot<Guid> base class:

  1. public class Book : AuditedAggregateRoot<Guid>
  2. {
  3. public string Name { get; set; }
  4. }

You can override the OnModelCreating method in your DbContext and configure the mapping as shown below:

  1. protected override void OnModelCreating(ModelBuilder builder)
  2. {
  3. //Always call the base method
  4. base.OnModelCreating(builder);
  5. builder.Entity<Book>(b =>
  6. {
  7. b.ToTable("Books");
  8. //Configure the base properties
  9. b.ConfigureByConvention();
  10. //Configure other properties (if you are using the fluent API)
  11. b.Property(x => x.Name).IsRequired().HasMaxLength(128);
  12. });
  13. }
  • Calling b.ConfigureByConvention() is important here to properly configure the base properties.
  • You can configure the Name property here or you can use the data annotation attributes (see the EF Core document).

While there are many extension methods to configure your base properties, ConfigureByConvention() internally calls them if necessary. So, it is enough to call it.

Configure the Connection String Selection

If you have multiple databases in your application, you can configure the connection string name for your DbContext using the [ConnectionStringName] attribute. Example:

  1. [ConnectionStringName("MySecondConnString")]
  2. public class MyDbContext : AbpDbContext<MyDbContext>
  3. {
  4. }

If you don’t configure, the Default connection string is used. If you configure a specific connection string name, but not define this connection string name in the application configuration then it fallbacks to the Default connection string (see the connection strings document for more information).

Registering DbContext To Dependency Injection

Use AddAbpDbContext method in your module to register your DbContext class for dependency injection system.

  1. using Microsoft.Extensions.DependencyInjection;
  2. using Volo.Abp.EntityFrameworkCore;
  3. using Volo.Abp.Modularity;
  4. namespace MyCompany.MyProject
  5. {
  6. [DependsOn(typeof(AbpEntityFrameworkCoreModule))]
  7. public class MyModule : AbpModule
  8. {
  9. public override void ConfigureServices(ServiceConfigurationContext context)
  10. {
  11. context.Services.AddAbpDbContext<MyDbContext>();
  12. //...
  13. }
  14. }
  15. }

Add Default Repositories

ABP can automatically create default generic repositories for the entities in your DbContext. Just use AddDefaultRepositories() option on the registration:

  1. services.AddAbpDbContext<MyDbContext>(options =>
  2. {
  3. options.AddDefaultRepositories();
  4. });

This will create a repository for each aggregate root entity (classes derived from AggregateRoot) by default. If you want to create repositories for other entities too, then set includeAllEntities to true:

  1. services.AddAbpDbContext<MyDbContext>(options =>
  2. {
  3. options.AddDefaultRepositories(includeAllEntities: true);
  4. });

Then you can inject and use IRepository<TEntity, TPrimaryKey> in your services. Assume that you have a Book entity with Guid primary key:

  1. public class Book : AggregateRoot<Guid>
  2. {
  3. public string Name { get; set; }
  4. public BookType Type { get; set; }
  5. }

(BookType is a simple enum here) And you want to create a new Book entity in a domain service:

  1. public class BookManager : DomainService
  2. {
  3. private readonly IRepository<Book, Guid> _bookRepository;
  4. //inject default repository to the constructor
  5. public BookManager(IRepository<Book, Guid> bookRepository)
  6. {
  7. _bookRepository = bookRepository;
  8. }
  9. public async Task<Book> CreateBook(string name, BookType type)
  10. {
  11. Check.NotNullOrWhiteSpace(name, nameof(name));
  12. var book = new Book
  13. {
  14. Id = GuidGenerator.Create(),
  15. Name = name,
  16. Type = type
  17. };
  18. //Use a standard repository method
  19. await _bookRepository.InsertAsync(book);
  20. return book;
  21. }
  22. }

This sample uses InsertAsync method to insert a new entity to the database.

Add Custom Repositories

Default generic repositories are powerful enough in most cases (since they implement IQueryable). However, you may need to create a custom repository to add your own repository methods. Assume that you want to delete all books by type.

It’s suggested to define an interface for your custom repository:

  1. public interface IBookRepository : IRepository<Book, Guid>
  2. {
  3. Task DeleteBooksByType(BookType type);
  4. }

You generally want to derive from the IRepository to inherit standard repository methods. However, you don’t have to. Repository interfaces are defined in the domain layer of a layered application. They are implemented in the data/infrastructure layer (EntityFrameworkCore project in a startup template).

Example implementation of the IBookRepository interface:

  1. public class BookRepository : EfCoreRepository<BookStoreDbContext, Book, Guid>, IBookRepository
  2. {
  3. public BookRepository(IDbContextProvider<BookStoreDbContext> dbContextProvider)
  4. : base(dbContextProvider)
  5. {
  6. }
  7. public async Task DeleteBooksByType(BookType type)
  8. {
  9. await DbContext.Database.ExecuteSqlRawAsync(
  10. $"DELETE FROM Books WHERE Type = {(int)type}"
  11. );
  12. }
  13. }

Now, it’s possible to inject the IBookRepository and use the DeleteBooksByType method when needed.

Override the Default Generic Repository

Even if you create a custom repository, you can still inject the default generic repository (IRepository<Book, Guid> for this example). Default repository implementation will not use the class you have created.

If you want to replace default repository implementation with your custom repository, do it inside the AddAbpDbContext options:

  1. context.Services.AddAbpDbContext<BookStoreDbContext>(options =>
  2. {
  3. options.AddDefaultRepositories();
  4. //Replaces IRepository<Book, Guid>
  5. options.AddRepository<Book, BookRepository>();
  6. });

This is especially important when you want to override a base repository method to customize it. For instance, you may want to override DeleteAsync method to delete a specific entity in a more efficient way:

  1. public override async Task DeleteAsync(
  2. Guid id,
  3. bool autoSave = false,
  4. CancellationToken cancellationToken = default)
  5. {
  6. //TODO: Custom implementation of the delete method
  7. }

Access to the EF Core API

In most cases, you want to hide EF Core APIs behind a repository (this is the main purpose of the repository pattern). However, if you want to access the DbContext instance over the repository, you can use GetDbContext() or GetDbSet() extension methods. Example:

  1. public class BookService
  2. {
  3. private readonly IRepository<Book, Guid> _bookRepository;
  4. public BookService(IRepository<Book, Guid> bookRepository)
  5. {
  6. _bookRepository = bookRepository;
  7. }
  8. public void Foo()
  9. {
  10. DbContext dbContext = _bookRepository.GetDbContext();
  11. DbSet<Book> books = _bookRepository.GetDbSet();
  12. }
  13. }
  • GetDbContext returns a DbContext reference instead of BookStoreDbContext. You can cast it, however in most cases you don’t need it.

Important: You must reference to the Volo.Abp.EntityFrameworkCore package from the project you want to access to the DbContext. This breaks encapsulation, but this is what you want in that case.

Extra Properties & Object Extension Manager

Extra Properties system allows you to set/get dynamic properties to entities those implement the IHasExtraProperties interface. It is especially useful when you want to add custom properties to the entities defined in an application module, when you use the module as package reference.

By default, all the extra properties of an entity are stored as a single JSON object in the database.

Entity extension system allows you to to store desired extra properties in separate fields in the related database table. For more information about the extra properties & the entity extension system, see the following documents:

This section only explains the EF Core related usage of the ObjectExtensionManager.

ObjectExtensionManager.Instance

ObjectExtensionManager implements the singleton pattern, so you need to use the static ObjectExtensionManager.Instance to perform all the operations.

MapEfCoreProperty

MapEfCoreProperty is a shortcut extension method to define an extension property for an entity and map to the database.

Example: Add Title property (database field) to the IdentityRole entity:

  1. ObjectExtensionManager.Instance
  2. .MapEfCoreProperty<IdentityRole, string>(
  3. "Title",
  4. (entityBuilder, propertyBuilder) =>
  5. {
  6. propertyBuilder.HasMaxLength(64);
  7. }
  8. );

If the related module has implemented this feature (by using the ConfigureEfCoreEntity explained below), then the new property is added to the model. Then you need to run the standard Add-Migration and Update-Database commands to update your database to add the new field.

MapEfCoreProperty method must be called before using the related DbContext. It is a static method. The best way is to use it in your application as earlier as possible. The application startup template has a YourProjectNameEfCoreEntityExtensionMappings class that is safe to use this method inside.

ConfigureEfCoreEntity

If you are building a reusable module and want to allow application developers to add properties to your entities, you can use the ConfigureEfCoreEntity extension method in your entity mapping. However, there is a shortcut extension method ConfigureObjectExtensions that can be used while configuring the entity mapping:

  1. builder.Entity<YourEntity>(b =>
  2. {
  3. b.ConfigureObjectExtensions();
  4. //...
  5. });

If you call ConfigureByConvention() extension method (like b.ConfigureByConvention() for this example), ABP Framework internally calls the ConfigureObjectExtensions method. It is a best practice to use the ConfigureByConvention() method since it also configures database mapping for base properties by convention.

See the “ConfigureByConvention Method“ section above for more information.

Advanced Topics

Set Default Repository Classes

Default generic repositories are implemented by EfCoreRepository class by default. You can create your own implementation and use it for all the default repository implementations.

First, define your default repository classes like that:

  1. public class MyRepositoryBase<TEntity>
  2. : EfCoreRepository<BookStoreDbContext, TEntity>
  3. where TEntity : class, IEntity
  4. {
  5. public MyRepositoryBase(IDbContextProvider<BookStoreDbContext> dbContextProvider)
  6. : base(dbContextProvider)
  7. {
  8. }
  9. }
  10. public class MyRepositoryBase<TEntity, TKey>
  11. : EfCoreRepository<BookStoreDbContext, TEntity, TKey>
  12. where TEntity : class, IEntity<TKey>
  13. {
  14. public MyRepositoryBase(IDbContextProvider<BookStoreDbContext> dbContextProvider)
  15. : base(dbContextProvider)
  16. {
  17. }
  18. }

First one is for entities with composite keys, second one is for entities with single primary key.

It’s suggested to inherit from the EfCoreRepository class and override methods if needed. Otherwise, you will have to implement all the standard repository methods manually.

Now, you can use SetDefaultRepositoryClasses option:

  1. context.Services.AddAbpDbContext<BookStoreDbContext>(options =>
  2. {
  3. options.SetDefaultRepositoryClasses(
  4. typeof(MyRepositoryBase<,>),
  5. typeof(MyRepositoryBase<>)
  6. );
  7. //...
  8. });

Set Base DbContext Class or Interface for Default Repositories

If your DbContext inherits from another DbContext or implements an interface, you can use that base class or interface as DbContext for default repositories. Example:

  1. public interface IBookStoreDbContext : IEfCoreDbContext
  2. {
  3. DbSet<Book> Books { get; }
  4. }

IBookStoreDbContext is implemented by the BookStoreDbContext class. Then you can use generic overload of the AddDefaultRepositories:

  1. context.Services.AddAbpDbContext<BookStoreDbContext>(options =>
  2. {
  3. options.AddDefaultRepositories<IBookStoreDbContext>();
  4. //...
  5. });

Now, your custom BookRepository can also use the IBookStoreDbContext interface:

  1. public class BookRepository : EfCoreRepository<IBookStoreDbContext, Book, Guid>, IBookRepository
  2. {
  3. //...
  4. }

One advantage of using an interface for a DbContext is then it will be replaceable by another implementation.

Replace Other DbContextes

Once you properly define and use an interface for DbContext, then any other implementation can replace it using the ReplaceDbContext option:

  1. context.Services.AddAbpDbContext<OtherDbContext>(options =>
  2. {
  3. //...
  4. options.ReplaceDbContext<IBookStoreDbContext>();
  5. });

In this example, OtherDbContext implements IBookStoreDbContext. This feature allows you to have multiple DbContext (one per module) on development, but single DbContext (implements all interfaces of all DbContexts) on runtime.

See Also