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,请参阅此文档

ABP框架系列之三:(Entity Framework Integration-实体框架集成)的更多相关文章

  1. Entity Framework(实体框架 EF)

    什么是Entity Framework呢(下面简称EF)? EF(实体框架)是ADO.NET中的一组支持开发面向数据的软件应用程序的技术,是微软的一个ORM框架.ORM(对象关系映射框架):指的是面向 ...

  2. 用 MVC 5 的 EF6 Code First 入门 系列:MVC程序中实体框架的Code First迁移和部署

    用 MVC 5 的 EF6 Code First 入门 系列:MVC程序中实体框架的Code First迁移和部署 这是微软官方SignalR 2.0教程Getting Started with En ...

  3. ASP.NET MVC深入浅出系列(持续更新) ORM系列之Entity FrameWork详解(持续更新) 第十六节:语法总结(3)(C#6.0和C#7.0新语法) 第三节:深度剖析各类数据结构(Array、List、Queue、Stack)及线程安全问题和yeild关键字 各种通讯连接方式 设计模式篇 第十二节: 总结Quartz.Net几种部署模式(IIS、Exe、服务部署【借

    ASP.NET MVC深入浅出系列(持续更新)   一. ASP.NET体系 从事.Net开发以来,最先接触的Web开发框架是Asp.Net WebForm,该框架高度封装,为了隐藏Http的无状态模 ...

  4. 21.翻译系列:Entity Framework 6 Power Tools【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/entity-framework-power-tools.aspx 大家好,这里就是EF ...

  5. [转]Entity Framework 的实体关系

    通过 Entiy Framework实践系列 文章,理了理 Entity Framework 的实体关系. 为什么要写文章来理清这些关系?“血”的教训啊,刚开始使用 Entity Framework  ...

  6. 基于Entity Framework 6的框架Nido Framework

    随着 Entity Framework 最新主版本 EF6 的推出,Microsoft 对象关系映射 (ORM) 工具达到了新的专业高度,与久负盛名的 .NET ORM 工具相比已不再是门外汉. EF ...

  7. 基于.NET的微软ORM框架视频教程(Entity Framework技术)

    基于.NET的微软ORM框架视频教程(Entity Framework技术) 第一讲  ORM映射 第二讲 初识EntifyFramework框架 第三讲 LINQ表达式查询 第四讲 LINQ方法查询 ...

  8. java日志框架系列(4):logback框架xml配置文件语法

    1.xml配置文件语法 由于logback配置文件语法特别灵活,因此无法用DTD或schema进行定义. 1.配置文件基本结构 配置文件基本结构:以<configuration>标签开头, ...

  9. ABP框架系列之三十九:(NLayer-Architecture-多层架构)

    Introduction Layering of an application's codebase is a widely accepted technique to help reduce com ...

随机推荐

  1. 涂抹mysql笔记-InnoDB/MyISAM及其它各种存储引擎

    存储引擎:一种设计的存取和处理方式.为不同访问特点的表对象指定不同的存储引擎,可以获取更高的性能和处理数据的灵活性.通常是.so文件,可以用mysql命令加载它. 查看当前mysql数据库支持的存储引 ...

  2. 01-简单编写http服务器

    package com.day3; import java.io.IOException; import java.io.InputStream; import java.net.ServerSock ...

  3. SpringBoot入门篇--关于properties和yml两种配置文件的一些事情

    我们在使用SpringBoot这个框架的时候都一定使用或者说是见到过application.properties或者是application.yml,经不住有人就会问这俩文件到底是什么情况,其实说白了 ...

  4. Celery 异步任务 , 定时任务 , 周期任务 的芹菜

    1.什么是Celery?Celery 是芹菜Celery 是基于Python实现的模块, 用于执行异步定时周期任务的其结构的组成是由    1.用户任务 app    2.管道 broker 用于存储 ...

  5. web.xml的加载过程配置详解

      一:web.xml加载过程 简单说一下,web.xml的加载过程.当我们启动一个WEB项目容器时,容器包括(JBoss,Tomcat等).首先会去读取web.xml配置文件里的配置,当这一步骤没有 ...

  6. python 处理 https链接 socket报错 链接https

    // socket 链接 https 有问题 得去看看ssl文档 用法 import socketimport ssl def https_test(url): proto = "http& ...

  7. Pycharm:使用笔记

    1.快捷键笔记 CTRL+D:复制当前行 CTRL+/:注释选中行 CTRL+ALT+L:自动format,自动进行标准格式化 ALT + 7:查看当前文件的类和方法概览 Ctrl + Y    删除 ...

  8. Centos Tomcat监控

    1.Window环境下jdk的bin目录中提供jvisualvm.exe工具,但是linux环境中的jdk未提供. 用window下的jvisualvm远程监控linux环境下的tomcat 两种连接 ...

  9. python 对象转字典

    从数据库中取出的数数据是 对象类型的,不能直接展示出来,需要转成字典类型,然后转成json 字符串,传给前端: data = {} data.update(obj.__dict__) print(da ...

  10. nginx 301跳转

    server { server_name xxxx.com; return 301 $scheme://www.xxxx.com$request_uri; }