当前位置:网站首页>ABP framework Practice Series (I) - Introduction to persistence layer
ABP framework Practice Series (I) - Introduction to persistence layer
2022-06-26 03:44:00 【yuyue5945】
- Data persistence
- Data persistence layer
- ORM
- ABP Framework of the Entity FrameWork Core
- ABP The warehouse of
- Precautions for storage
- Blogger GitHub Address
- Pay attention to the official account, leaving your confusion or insight
Data persistence
Before we start with the persistence layer , Let's start with a basic concept : Persistence
In a narrow sense : “ Persistence ” It only means to save the domain object permanently to the database ; In a broad sense ,“ Persistence ” Including various operations related to database ( Persistence is to save useful data with some technology , It can be used again in the future , Database technology , Save the memory data in the form of a file in a permanent medium ( Disks, etc ) It's all about persistence .
But only persistence will make the project not maintainable or not maintainable , The simple saving function can't satisfy the modularity of software development 、 Maintainability 、
Extensibility 、 The principle of stratification , So we need a technical framework , Make the operation saved between business layer and database maintainable 、 Extensibility 、 Stratification , And then there was “ Persistence layer ” The concept of
Data persistence layer
Persistence layer : The design goal is to provide a link between the high and low levels for the whole project 、 Unified 、 Secure and concurrent data persistence mechanism , Complete the programming work of persisting various databases , And provide services for system business logic . The data persistence layer provides data access methods , It can make programmers avoid manually writing programs to access the data persistence layer , Focus on business logic development , And can reuse mapping framework in different projects , It greatly simplifies the development process of data addition, deletion, modification and query , At the same time, it does not lose the natural advantages of multilayer structure , Scalable and scalable
ORM
ORM A seed implementation of the data persistence layer , It's through the mechanism of mapping , Treat a record in the database as a class of the program , In this way CURD On the disposal , Real object-oriented development , It also greatly shortens the later maintenance cycle of the software
On the market .Net Core ORM There are so many tools , Here are four common frameworks , It's used in the same way , This is a very good article on the chain EF Core Getting started with :
EntityFrameWork Core( Recommend the official account , Dry cargo is full. )
[FreeSql]
[Nhibernate-core]
[MyBatis]
ORM Advantages and disadvantages
- advantage
- ORM The biggest advantage , Hide data access details ,“ closed ” General database interaction of ,ORM At the heart of . It makes our general database interaction easy , And don't even think about the damned SQL sentence . Rapid development of , From this came .
- ORM It makes it easy for us to construct solid data structure . stay ORM The prehistoric era of chronology , We need to transform our object model one by one SQL sentence , Through direct connection or DB helper Construct our database system in relational database . And now , Basically all ORM Framework provides the function of constructing relational database structure through object model .
- shortcoming
- For complex queries ,ORM Still can't do it . Although it can be achieved , But it's not worth it . Views can solve most of the calculated column,case ,group,having,order by, exists
ABP Framework of the Entity FrameWork Core
DbContext
EF The core needs to be defined from DbContext class . stay ABP, We should start from abpdbcontext get , As shown below
public class MyDbContext : AbpDbContext
{
public DbSet<Product> Products {
get; set; }
public MyDbContext(DbContextOptions<MyDbContext> options)
: base(options)
{
}
}
Constructor must get DbContextOptions As shown above . The parameter name must be an option . Can't change it , because ABP Provide it as an anonymous object parameter .
Configuration( Configuration database connection string )
ABP Module Zero in , Configure the path in appsettings.json In file The configuration format is basically as follows
"ConnectionStrings": {
"Default": "Data Source = 10.28.253.2;Initial Catalog = EventCloudDb;User Id = sa;Password = Ecsgui123;"
}
And loading the configuration file 、 as well as DbContext The registration of is done through the following code (ABP Default generation )
In the code ,EFModule Inherited from ABPModule, Table name EF This module , It's a pluggable module , There are three initialization functions under this module PreInitialize( Pre initialization )、Initialize( initialization )、PostInitialize(StartUp Execute after completion ).
among ,PreInitilize In the method , contain ABP Under the framework of the module AbpEFCore Module registration .
[DependsOn(
typeof(UniversalCoreModule),
typeof(AbpZeroCoreEntityFrameworkCoreModule))]
public class UniversalEntityFrameworkModule : AbpModule
{
/* Used it tests to skip dbcontext registration, in order to use in-memory database of EF Core */
public bool SkipDbContextRegistration {
get; set; }
public bool SkipDbSeed {
get; set; }
public override void PreInitialize()
{
if (!SkipDbContextRegistration)
{
Configuration.Modules.AbpEfCore().AddDbContext<UniversalDbContext>(options =>
{
if (options.ExistingConnection != null)
{
UniversalDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
}
else
{
UniversalDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
}
});
}
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(typeof(UniversalEntityFrameworkModule).GetAssembly());
}
public override void PostInitialize()
{
if (!SkipDbSeed)
{
SeedHelper.SeedHostDb(IocManager);
}
}
}
After getting familiar with the above DbContext After loading the configuration process , We will come to create DbContext part , This part ,ABP Template in UniversalDbContextFactory in , Implements the object DbContext The creation of
1、 establish DbContextOptionBuilder establish
2、 Load configuration file information into memory
3、 initialization Builder Information
4、new A new DbContext object
public class Git_ECSGUI_UniversalDbContextFactory : IDesignTimeDbContextFactory<Git_ECSGUI_UniversalDbContext>
{
public Git_ECSGUI_UniversalDbContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<Git_ECSGUI_UniversalDbContext>();
var configuration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
Git_ECSGUI_UniversalDbContextConfigurer.Configure(builder, configuration.GetConnectionString(Git_ECSGUI_UniversalConsts.ConnectionStringName));
return new Git_ECSGUI_UniversalDbContext(builder.Options);
}
}
ABP The warehouse of
Finished EF Core Medium DbContext stay ABP The creation process in , We turn our attention to Repositories( Warehouse ) Come here in the middle , It's a bridge between the domain layer and persistence , Repositories are used to abstract data access from a high level .
stay ABP The medium between the domain and persistence layer in the framework , Using a collection like interface to access entities , Every entity ( Or aggregate roots ) Use for a separate warehouse
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-z5RnnJFE-1609164055699)(https://i.loli.net/2020/12/28/EtWBnGiP1v7UeMY.png)]
Default warehouse
stay ABP in , A warehouse class implements IRepository<TEntity,TPrimaryKey> Interface .ABP By default, a default repository is automatically created for each entity type . You can inject it directly IRepository( or IRepository<TEntity,TPrimaryKey>). An example of an application service using warehousing to insert an entity into a database :PersonService Constructor Injection IRepository And use Insert Method .
public class PersonService : IPersonService
{
private readonly IRepository<Person> _personRepository;
public PersonService(IRepository<Person> personRepository)
{
_personRepository = personRepository;
}
public void CreatePerson(CreatePersonInput input)
{
person = new Person {
Name = input.Name, EmailAddress = input.EmailAddress };
_personRepository.Insert(person);
}
}
Custom warehousing
Only when the entity needs to create a custom warehousing method , You need to create a storage class .
public abstract class Git_ECSGUI_UniversalRepositoryBase<TEntity, TPrimaryKey> : EfCoreRepositoryBase<Git_ECSGUI_UniversalDbContext, TEntity, TPrimaryKey>
where TEntity : class, IEntity<TPrimaryKey>
{
protected Git_ECSGUI_UniversalRepositoryBase(IDbContextProvider<Git_ECSGUI_UniversalDbContext> dbContextProvider)
: base(dbContextProvider)
{
}
// Add your common methods for all repositories
}
/// <summary>
/// Base class for custom repositories of the application.
/// This is a shortcut of <see cref="Git_ECSGUI_UniversalRepositoryBase{TEntity,TPrimaryKey}"/> for <see cref="int"/> primary key.
/// </summary>
/// <typeparam name="TEntity">Entity type</typeparam>
public abstract class Git_ECSGUI_UniversalRepositoryBase<TEntity> : Git_ECSGUI_UniversalRepositoryBase<TEntity, int>, IRepository<TEntity>
where TEntity : class, IEntity<int>
{
protected Git_ECSGUI_UniversalRepositoryBase(IDbContextProvider<Git_ECSGUI_UniversalDbContext> dbContextProvider)
: base(dbContextProvider)
{
}
// Do not add any method here, add to the class above (since this inherits it)!!!
}
To implement a custom Repository , Just get it from the application specific underlying repository class created above .
public interface IUniversalTaskRepository : IRepository<Task>
{
List<Task> GetTaskByAssignedPersonId(long taskId);
}
public UniversalTaskRepository:Git_ECSGUI_UniversalRepositoryBase, IUniversalTaskRepository
{
public UniversalTaskRepository(IDbContextProvider<Git_ECSGUI_UniversalDbContext> dbContextProvider) : base(dbContextProvider)
{
}
/// <summary>
/// Get the tasks assigned by a user
/// </summary>
/// <param name="personId"> user Id</param>
/// <returns> Task list </returns>
public List<Task> GetUniversalTaskId(long taskId)
{
var query = GetAll();
if (taskId > 0)
{
query = query.Where(t => t.taskid == taskId);
}
return query.ToList();
}
}
Precautions for storage
- In the warehousing method ,ABP Automatically open and close the database connection .
- When the warehouse method is called , The database connection opens automatically and the transaction starts .
- When a warehousing method calls another warehousing method , They actually share the same database connection and transaction .
- Storage objects are temporary , because IRepository The interface is inherited by default from ITransientDependency Interface . therefore , Storage objects can only be injected when necessary , Only by Ioc The container automatically creates new instances .
- The default generic repository can meet most of our needs . It's only when you're not satisfied , To create a customized warehouse .
Blogger GitHub Address
https://github.com/yuyue5945
Pay attention to the official account, leaving your confusion or insight

边栏推荐
- MySQL高级部分( 四: 锁机制、SQL优化 )
- MySQL addition, deletion, query and modification (Advanced)
- 拖放
- View of MySQL
- kotlin快速上手
- Is it safe for individuals to buy stocks with flush software? How to buy stocks
- Cultivate children's creativity under the concept of project steam Education
- USB peripheral driver - Enumeration
- Insect structure and Deconstruction
- MySQL advanced part (IV: locking mechanism and SQL optimization)
猜你喜欢

计组笔记——CPU的指令流水

Todolist incomplete, completed

"Renegotiation" agreement

MySQL高級篇第一章(linux下安裝MySQL)【下】

Digital twin intelligent water service, breaking through the development dilemma of sponge City

拖放

Partition, column, list

Deletelater Usage Summary in QT

Uni app custom selection date 1 (September 16, 2021)

Camera-memory内存泄漏分析(三)
随机推荐
Qixia fire department carries out fire safety training on construction site
Popupwindow utility class
Multimedia elements, audio, video
Request object, send request
Uni app, the text implementation expands and retracts the full text
MySQL addition, deletion, query and modification (primary level)
Uni app swiper rotation chart (full screen / card)
面试阿里测开岗失败后,被面试官在朋友圈吐槽了......(心塞)
WebRTC系列-网络传输之7-ICE补充之偏好(preference)与优先级(priority)
路由跳转之点击列表的操作按钮,跳转至另一个菜单页面并激活相应的菜单
Tupu software is the digital twin of offshore wind power, striving to be the first
kotlin快速上手
动态线段树leetcode.715
Digital twin intelligent water service, breaking through the development dilemma of sponge City
USB peripheral driver - Enumeration
Android gap animation translate, scale, alpha, rotate
[paper notes] learning to grasp with primitive shaped object policies
How to prepare for a moving wedding
Solve the problem that the input box is blocked by the pop-up keyboard under the WebView transparent status bar
Mysql database foundation