ABP框架系列之三:(Entity Framework Integration-实体框架集成)

时间:2023-12-16 20:16:20

ASP.NET Boilerplate can work with any O/RM framework. It has built-in integration with EntityFramework. This document will explain how to use EntityFramework with ASP.NET Boilerplate. It's assumed that you're already familar with EntityFramework in a basic level.

ASP.NET样板可以与任何O / RM工作框架。它具有内置的集成EntityFramework。本文档将解释如何使用EntityFramework ASP.NET样板。假定你已经熟悉了基本的EntityFramework。

Nuget Package

Nuget package to use EntityFramework as O/RM in ASP.NET Boilerplate is Abp.EntityFramework. You should add it to your application. It's better to implement EntityFramework in a seperated assembly (dll) in your application and depend on that package from this assembly.

使用EntityFramework NuGet包在ASP.NET样板的O / RM是Abp.EntityFramework。你应该把它添加到你的应用程序中。最好是在一个分离的组件实现EntityFramework(DLL)在你的应用和依赖这个组件包。

DbContext

As you know, to work with EntityFramework, you should define a DbContext class for your application. An example DbContext is shown below:

你知道的,和EntityFramework一起工作,你应该定义一个应用程序的DbContext类。例DbContext如下所示:

public class SimpleTaskSystemDbContext : AbpDbContext
{
public virtual IDbSet<Person> People { get; set; }
public virtual IDbSet<Task> Tasks { get; set; } public SimpleTaskSystemDbContext()
: base("Default")
{ } public SimpleTaskSystemDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{ } public SimpleTaskSystemDbContext(DbConnection existingConnection)
: base(existingConnection, false)
{ } public SimpleTaskSystemDbContext(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{ } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder); modelBuilder.Entity<Person>().ToTable("StsPeople");
modelBuilder.Entity<Task>().ToTable("StsTasks").HasOptional(t => t.AssignedPerson);
}
}

It's a regular DbContext class except following rules:

这是一个常规的DbContext类除以下规则:

  • It's derived from AbpDbContext instead of DbContext.
  • 这是得到abpdbcontext替代 DbContext 。
  • It should have constructors as the sample above (constructor parameter names should also be same). Explanation:
  • 它应该有构造函数作为上面的示例(构造函数形参名称也应该相同)。解释:
    • Default consturctor passes "Default" to base bass as the connection string. So, it expects a "Default" named connection string in the web.config/app.config file. This constructor is not used by ABP, but used by EF command line migration tool commands (like update-database).
    • The constructor gets nameOrConnectionString is used by ABP to pass the connection name or string on runtime.
    • The constructor get existingConnection can be used for unit test and not directly used by ABP.
    • The constructor gets existingConnection and contextOwnsConnection is used by ABP on single database multiple dbcontext scenarios to share same connection & transaction () whenDbContextEfTransactionStrategy is used (see Transaction Management section below).
    • 默认构造函数通过“默认”基础低音的连接字符串。因此,预计“默认”的web.config/app.config文件命名连接字符串。这个构造函数不是由ABP使用的,而是由EF命令行迁移工具命令(如更新数据库)使用的。
      构造函数获取nameorconnectionstring采用ABP在运行时通过连接字符串的名称。
      让existingconnection构造函数可用于单元测试并不是直接使用ABP。
      构造函数获取existingconnection和contextownsconnection的ABP单数据库的多个DbContext场景用来分享相同的连接和交易dbcontexteftransactionstrategy时使用(见交易管理部分)。

EntityFramework can map classes to database tables in a conventional way. You even don't need to make any configuration unless you make some custom stuff. In this example, we mapped entities to different tables. As default, Task entity maps to Tasks table. But we changed it to be StsTasks table. Instead of configuring it with data annotation attributes, I prefered to use fluent configuration. You can choice the way you like.

EF框架可以类映射到数据库表中的一个常规的方式。你甚至不需要做任何配置,除非你做一些定制的东西。在本例中,我们将实体映射到不同的表中。默认情况下,任务实体映射到任务表。但我们把它换成ststasks表。我不喜欢使用数据注释属性来配置它,而是倾向于使用流畅的配置。你可以选择你喜欢的方式。

Repositories(仓库)

Repositories are used to abstract data access from higher layers. See repository documentation for more.

存储库用于从高层抽象数据访问。更多信息请参见库文档。

Default Repositories

Abp.EntityFramework implements default repositories for all entities defined in your DbContext. You don't have to create repository classes to use predefined repository methods. Example:

abp.entityframework实现在你定义的所有实体的默认库DbContext。您不必创建存储库类以使用预定义的存储库方法。例子:

public class PersonAppService : IPersonAppService
{
private readonly IRepository<Person> _personRepository; public PersonAppService(IRepository<Person> personRepository)
{
_personRepository = personRepository;
} public void CreatePerson(CreatePersonInput input)
{
person = new Person { Name = input.Name, EmailAddress = input.EmailAddress }; _personRepository.Insert(person);
}
}

PersonAppService contructor-injects IRepository<Person> and uses the Insert method. In this way, you can easily inject IRepository<TEntity> (or IRepository<TEntity, TPrimaryKey>) and use predefined methods.

personappservice构造函数注入IRepository <person>采用插入法。这样,你可以很容易地注入IRepository < tentity >(或< tentity IRepository,tprimarykey >),使用预定义的方法。

Custom Repositories

If standard repository methods are not sufficient, you can create custom repository classes for your entities.

如果标准存储库方法还不够,您可以为实体创建自定义存储库类。

Application Specific Base Repository Class

ASP.NET Boilerplate provides a base class EfRepositoryBase to implement repositories easily. To implement IRepository interface, you can just derive your repository from this class. But it's better to create your own base class that extens EfRepositoryBase. Thus, you can add shared/common methods to your repositories or override existing methods easily. An example base class all for repositories of a SimpleTaskSystem application:

ASP.NET的模板提供了一个基类库efrepositorybase实现容易。实施IRepository接口,你可以从这个类派生你的库。但它更好地创建自己的基地班extens EfRepositoryBase。因此,您可以将共享/公共方法添加到存储库中,或者轻松地覆盖现有的方法。例基类的所有simpletasksystem应用库:

//Base class for all repositories in my application
public class SimpleTaskSystemRepositoryBase<TEntity, TPrimaryKey> : EfRepositoryBase<SimpleTaskSystemDbContext, TEntity, TPrimaryKey>
where TEntity : class, IEntity<TPrimaryKey>
{
public SimpleTaskSystemRepositoryBase(IDbContextProvider<SimpleTaskSystemDbContext> dbContextProvider)
: base(dbContextProvider)
{
} //add common methods for all repositories
} //A shortcut for entities those have integer Id
public class SimpleTaskSystemRepositoryBase<TEntity> : SimpleTaskSystemRepositoryBase<TEntity, int>
where TEntity : class, IEntity<int>
{
public SimpleTaskSystemRepositoryBase(IDbContextProvider<SimpleTaskSystemDbContext> dbContextProvider)
: base(dbContextProvider)
{
} //do not add any method here, add to the class above (because this class inherits it)
}

Notice that we're inheriting from EfRepositoryBase<SimpleTaskSystemDbContext, TEntity, TPrimaryKey>. This declares to ASP.NET Boilerplate to use SimpleTaskSystemDbContext in our repositories.

注意,我们从efrepositorybase < simpletasksystemdbcontext,TEntity继承,tprimarykey >。这是ASP.NET的样板在我们的库使用simpletasksystemdbcontext。

By default, all repositories for your given DbContext (SimpleTaskSystemDbContext in this example) is implemented using EfRepositoryBase. You can replace it to your own repository base repository class by addingAutoRepositoryTypes attribute to your DbContext as shown below:

默认情况下,你指定的DbContext所有仓库(simpletasksystemdbcontext这个例子)是用efrepositorybase。你可以换到你自己的库库类的属性你addingautorepositorytypes DbContext如下所示:

[AutoRepositoryTypes(
typeof(IRepository<>),
typeof(IRepository<,>),
typeof(SimpleTaskSystemEfRepositoryBase<>),
typeof(SimpleTaskSystemEfRepositoryBase<,>)
)]
public class SimpleTaskSystemDbContext : AbpDbContext
{
...
}
Custom Repository Example

To implement a custom repository, just derive from your application specific base repository class we created above.

Assume that we have a Task entity that can be assigned to a Person (entity) and a Task has a State (new, assigned, completed... and so on). We may need to write a custom method to get list of Tasks with some conditions and with AssisgnedPerson property pre-fetched (included) in a single database query. See the example code:

要实现自定义存储库,只需从上面创建的应用程序特定的基础存储库类中获得。

假设我们有一个任务实体可以分配给一个人(实体),任务有一个状态(新的,分配的,完成的)…等等)。我们需要写一个获得有条件的任务列表的自定义方法和属性assisgnedperson预取(包括)在一个单一的数据库查询。请参见示例代码:

public interface ITaskRepository : IRepository<Task, long>
{
List<Task> GetAllWithPeople(int? assignedPersonId, TaskState? state);
} public class TaskRepository : SimpleTaskSystemRepositoryBase<Task, long>, ITaskRepository
{
public TaskRepository(IDbContextProvider<SimpleTaskSystemDbContext> dbContextProvider)
: base(dbContextProvider)
{
} public List<Task> GetAllWithPeople(int? assignedPersonId, TaskState? state)
{
var query = GetAll(); if (assignedPersonId.HasValue)
{
query = query.Where(task => task.AssignedPerson.Id == assignedPersonId.Value);
} if (state.HasValue)
{
query = query.Where(task => task.State == state);
} return query
.OrderByDescending(task => task.CreationTime)
.Include(task => task.AssignedPerson)
.ToList();
}
}

We first defined ITaskRepository and then implemented it. GetAll() returns IQueryable<Task>, then we can add some Where filters using given parameters. Finally we can call ToList() to get list of Tasks.

You can also use Context object in repository methods to reach to your DbContext and directly use Entity Framework APIs.

Note: Define the custom repository interface in the domain/core layer, implement it in the EntityFramework project for layered applications. Thus, you can inject the interface from any project without referencing to EF.

我们首先定义itaskrepository然后实现它。getall()返回IQueryable <任务>,然后我们可以添加一些过滤器使用给定的参数。最后,我们可以称tolist()得到任务列表。

你也可以在库的方法使用上下文对象到你的DbContext和直接使用实体框架的API。

注:定义域/核心层的自定义库的接口,实现其在EntityFramework的项目分层中的应用。因此,您可以在不引用EF的情况下从任何项目注入接口。

Repository Best Practices

  • Use default repositories wherever it's possible. You can use default repository even you have a custom repository for an entity (if you will use standard repository methods).
  • Always create repository base class for your application for custom repositories, as defined above.
  • Define interfaces for your custom repositories in domain layer (.Core project in startup template), custom repository classes in .EntityFramework project if you want to abstract EF from your domain/application.
  • 在可能的地方使用默认存储库。您可以使用默认存储库,即使您有实体的自定义存储库(如果您使用标准存储库方法)。
    始终为您的自定义存储库应用程序创建存储库基类,如上所述。
    定义自定义库在领域层的接口(在启动模板核心项目),自定义库类的。如果你想从你的摘要EF域/应用项目EntityFramework。

Transaction Management(事务管理)

ASP.NET Boilerplate has a built-in unit of work system to manage database connection and transactions. Entity framework has different transaction management approaches. ASP.NET Boilerplate uses ambient TransactionScope approach by default, but also has a built-in implementation for DbContext transaction API. If you want to switch to DbContext transaction API, you can configure it in PreInitialize method of your module like that:

ASP.NET的模板有一个内置的工作单元的系统来管理数据库连接和交易。实体框架有不同的事务管理方法。ASP.NET样板使用环境事务处理方法在默认情况下,但也有一个内置的DbContext API实现交易。如果你想切换到DbContext事务API,你可以配置它在你喜欢的方法分发模块:

Configuration.ReplaceService<IEfTransactionStrategy, DbContextEfTransactionStrategy>(DependencyLifeStyle.Transient);

Remember to add "using Abp.Configuration.Startup;" to your code file to be able to use ReplaceService generic extension method.

In addition, your DbContext should have constructors as described in DbContext section of this document.

记得添加“using Abp.Configuration.Startup;“你的代码文件,可以使用replaceservice通用的扩展方法。

此外,你应该在DbContext构造函数DbContext部分描述本文件。

Data Stores(数据存储)

Since ASP.NET Boilerplate has built-in integration with EntityFramework, it can work with data stores EntityFramework supports. Our free startup templates are designed to work with Sql Server but you can modify them to work with a different data store.

For example, if you want to work with MySql, please refer to this document

自从ASP.NET样板与EntityFramework有内置的集成,它可以与数据存储EntityFramework支持工作。我们的免费启动模板设计为与SQL Server一起工作,但您可以修改它们以与不同的数据存储一起工作。

例如,如果您想使用mysql,请参阅此文档