添加应用Microsoft.EntityFrameworkCore;Microsoft.EntityFrameworkCore.Design;Microsoft.EntityFrameworkCore.SqlServer

base类

  1. public abstract partial class BaseEntity
  2. {
  3. /// <summary>
  4. /// id
  5. /// </summary>
  6. public Guid gid { get; set; }
  7. }

分装仓储结构接口

  1. /// <summary>
  2. /// 仓储db接口
  3. /// </summary>
  4. public partial interface IDbContext
  5. {
  6. #region 方法
  7. /// <summary>
  8. /// 创建可用于查询和保存实体实例的DbSet
  9. /// </summary>
  10. /// <typeparam name="TEntity">Entity type</typeparam>
  11. /// <returns>A set for the given entity type</returns>
  12. DbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity;
  13.  
  14. /// <summary>
  15. /// 将在此上下文中所做的所有更改保存到数据库
  16. /// </summary>
  17. /// <returns>The number of state entries written to the database</returns>
  18. int SaveChanges();
  19.  
  20. /// <summary>
  21. /// 生成一个脚本,为当前模型创建所有表
  22. /// </summary>
  23. /// <returns>A SQL script</returns>
  24. string GenerateCreateScript();
  25.  
  26. /// <summary>
  27. /// 基于原始SQL查询为查询类型创建LINQ查询
  28. /// </summary>
  29. /// <typeparam name="TQuery">Query type</typeparam>
  30. /// <param name="sql">The raw SQL query</param>
  31. /// <returns>An IQueryable representing the raw SQL query</returns>
  32. IQueryable<TQuery> QueryFromSql<TQuery>(string sql) where TQuery : class;
  33.  
  34. /// <summary>
  35. /// 基于原始SQL查询为实体创建LINQ查询
  36. /// </summary>
  37. /// <typeparam name="TEntity">Entity type</typeparam>
  38. /// <param name="sql">The raw SQL query</param>
  39. /// <param name="parameters">The values to be assigned to parameters</param>
  40. /// <returns>An IQueryable representing the raw SQL query</returns>
  41. IQueryable<TEntity> EntityFromSql<TEntity>(string sql, params object[] parameters) where TEntity : BaseEntity;
  42.  
  43. /// <summary>
  44. /// 对数据库执行给定的SQL
  45. /// </summary>
  46. /// <param name="sql">The SQL to execute</param>
  47. /// <param name="doNotEnsureTransaction">true - the transaction creation is not ensured; false - the transaction creation is ensured.</param>
  48. /// <param name="timeout">The timeout to use for command. Note that the command timeout is distinct from the connection timeout, which is commonly set on the database connection string</param>
  49. /// <param name="parameters">Parameters to use with the SQL</param>
  50. /// <returns>The number of rows affected</returns>
  51. int ExecuteSqlCommand(RawSqlString sql, bool doNotEnsureTransaction = false, int? timeout = null, params object[] parameters);
  52.  
  53. /// <summary>
  54. /// 从上下文中分离一个实体
  55. /// </summary>
  56. /// <typeparam name="TEntity">Entity type</typeparam>
  57. /// <param name="entity">Entity</param>
  58. void Detach<TEntity>(TEntity entity) where TEntity : BaseEntity;
  59. #endregion
  60. }
  1. /// <summary>
  2. /// 基础仓储接口
  3. /// </summary>
  4. public partial interface IRepository<TEntity> where TEntity : BaseEntity
  5. {
  6. #region 方法
  7. /// <summary>
  8. /// 查询对象
  9. /// </summary>
  10. TEntity GetById(object gid);
  11.  
  12. /// <summary>
  13. /// 添加
  14. /// </summary>
  15. void Insert(TEntity entity);
  16.  
  17. /// <summary>
  18. /// 批量添加
  19. /// </summary>
  20. void Insert(IEnumerable<TEntity> entities);
  21.  
  22. /// <summary>
  23. /// 修改
  24. /// </summary>
  25. void Update(TEntity entity);
  26.  
  27. /// <summary>
  28. /// 批量修改
  29. /// </summary>
  30. void Update(IEnumerable<TEntity> entities);
  31.  
  32. /// <summary>
  33. /// 删除
  34. /// </summary>
  35. void Delete(TEntity entity);
  36.  
  37. /// <summary>
  38. /// 批量删除
  39. /// </summary>
  40. void Delete(IEnumerable<TEntity> entities);
  41. #endregion
  42.  
  43. #region 属性
  44. /// <summary>
  45. /// 查询数据集
  46. /// </summary>
  47. IQueryable<TEntity> Table { get; }
  48.  
  49. /// <summary>
  50. /// 获取一个启用“no tracking”(EF特性)的表,仅当您仅为只读操作加载记录时才使用它
  51. /// </summary>
  52. IQueryable<TEntity> TableNoTracking { get; }
  53. #endregion
  54. }
  1. /// <summary>
  2. /// 基础仓储实现
  3. /// </summary>
  4. public partial class EfRepository<TEntity> : IRepository<TEntity> where TEntity : BaseEntity
  5. {
  6. #region 参数
  7. private readonly IDbContext _context;
  8. private DbSet<TEntity> _entities;
  9. #endregion
  10.  
  11. #region 构造函数
  12. public EfRepository(IDbContext context)
  13. {
  14. this._context = context;
  15. }
  16. #endregion
  17.  
  18. #region 公共方法
  19. /// <summary>
  20. /// 实体更改的回滚并返回完整的错误消息
  21. /// </summary>
  22. /// <param name="exception">Exception</param>
  23. /// <returns>Error message</returns>
  24. protected string GetFullErrorTextAndRollbackEntityChanges(DbUpdateException exception)
  25. {
  26. //回滚实体
  27. if (_context is DbContext dbContext)
  28. {
  29. var entries = dbContext.ChangeTracker.Entries()
  30. .Where(e => e.State == EntityState.Added || e.State == EntityState.Modified).ToList();
  31.  
  32. entries.ForEach(entry => entry.State = EntityState.Unchanged);
  33. }
  34. _context.SaveChanges();
  35. return exception.ToString();
  36. }
  37. #endregion
  38.  
  39. #region 方法
  40. /// <summary>
  41. /// 按id获取实体
  42. /// </summary>
  43. /// <param name="id">Identifier</param>
  44. /// <returns>Entity</returns>
  45. public virtual TEntity GetById(object id)
  46. {
  47. return Entities.Find(id);
  48. }
  49.  
  50. /// <summary>
  51. /// 添加
  52. /// </summary>
  53. /// <param name="entity">Entity</param>
  54. public virtual void Insert(TEntity entity)
  55. {
  56. if (entity == null)
  57. throw new ArgumentNullException(nameof(entity));
  58.  
  59. try
  60. {
  61. Entities.Add(entity);
  62. _context.SaveChanges();
  63. }
  64. catch (DbUpdateException exception)
  65. {
  66. //ensure that the detailed error text is saved in the Log
  67. throw new Exception(GetFullErrorTextAndRollbackEntityChanges(exception), exception);
  68. }
  69. }
  70.  
  71. /// <summary>
  72. /// 批量添加
  73. /// </summary>
  74. /// <param name="entities">Entities</param>
  75. public virtual void Insert(IEnumerable<TEntity> entities)
  76. {
  77. if (entities == null)
  78. throw new ArgumentNullException(nameof(entities));
  79.  
  80. try
  81. {
  82. Entities.AddRange(entities);
  83. _context.SaveChanges();
  84. }
  85. catch (DbUpdateException exception)
  86. {
  87. //ensure that the detailed error text is saved in the Log
  88. throw new Exception(GetFullErrorTextAndRollbackEntityChanges(exception), exception);
  89. }
  90. }
  91.  
  92. /// <summary>
  93. /// 修改
  94. /// </summary>
  95. /// <param name="entity">Entity</param>
  96. public virtual void Update(TEntity entity)
  97. {
  98. if (entity == null)
  99. throw new ArgumentNullException(nameof(entity));
  100.  
  101. try
  102. {
  103. Entities.Update(entity);
  104. _context.SaveChanges();
  105. }
  106. catch (DbUpdateException exception)
  107. {
  108. //ensure that the detailed error text is saved in the Log
  109. throw new Exception(GetFullErrorTextAndRollbackEntityChanges(exception), exception);
  110. }
  111. }
  112.  
  113. /// <summary>
  114. /// 批量修改
  115. /// </summary>
  116. /// <param name="entities">Entities</param>
  117. public virtual void Update(IEnumerable<TEntity> entities)
  118. {
  119. if (entities == null)
  120. throw new ArgumentNullException(nameof(entities));
  121.  
  122. try
  123. {
  124. Entities.UpdateRange(entities);
  125. _context.SaveChanges();
  126. }
  127. catch (DbUpdateException exception)
  128. {
  129. //ensure that the detailed error text is saved in the Log
  130. throw new Exception(GetFullErrorTextAndRollbackEntityChanges(exception), exception);
  131. }
  132. }
  133.  
  134. /// <summary>
  135. /// 删除
  136. /// </summary>
  137. /// <param name="entity">Entity</param>
  138. public virtual void Delete(TEntity entity)
  139. {
  140. if (entity == null)
  141. throw new ArgumentNullException(nameof(entity));
  142.  
  143. try
  144. {
  145. Entities.Remove(entity);
  146. _context.SaveChanges();
  147. }
  148. catch (DbUpdateException exception)
  149. {
  150. //ensure that the detailed error text is saved in the Log
  151. throw new Exception(GetFullErrorTextAndRollbackEntityChanges(exception), exception);
  152. }
  153. }
  154.  
  155. /// <summary>
  156. /// 批量删除
  157. /// </summary>
  158. /// <param name="entities">Entities</param>
  159. public virtual void Delete(IEnumerable<TEntity> entities)
  160. {
  161. if (entities == null)
  162. throw new ArgumentNullException(nameof(entities));
  163.  
  164. try
  165. {
  166. Entities.RemoveRange(entities);
  167. _context.SaveChanges();
  168. }
  169. catch (DbUpdateException exception)
  170. {
  171. //ensure that the detailed error text is saved in the Log
  172. throw new Exception(GetFullErrorTextAndRollbackEntityChanges(exception), exception);
  173. }
  174. }
  175.  
  176. #endregion
  177.  
  178. #region 属性
  179. /// <summary>
  180. /// 获取表
  181. /// </summary>
  182. public virtual IQueryable<TEntity> Table => Entities;
  183.  
  184. /// <summary>
  185. /// 获取一个启用“no tracking”(EF特性)的表,仅当您仅为只读操作加载记录时才使用它
  186. /// </summary>
  187. public virtual IQueryable<TEntity> TableNoTracking => Entities.AsNoTracking();
  188.  
  189. /// <summary>
  190. /// 获取设置模板
  191. /// </summary>
  192. protected virtual DbSet<TEntity> Entities
  193. {
  194. get
  195. {
  196. if (_entities == null)
  197. _entities = _context.Set<TEntity>();
  198.  
  199. return _entities;
  200. }
  201. }
  202. #endregion
  203. }

ef的模型映射封装

  1. /// <summary>
  2. /// 表示数据库上下文模型映射配置
  3. /// </summary>
  4. public partial interface IMappingConfiguration
  5. {
  6. /// <summary>
  7. /// 应用此映射配置
  8. /// </summary>
  9. /// <param name="modelBuilder">用于构造数据库上下文模型的生成器</param>
  10. void ApplyConfiguration(ModelBuilder modelBuilder);
  11. }
  1. /// <summary>
  2. /// 表示基本实体映射配置
  3. /// </summary>
  4. /// <typeparam name="TEntity">Entity type</typeparam>
  5. public partial class NopEntityTypeConfiguration<TEntity> : IMappingConfiguration, IEntityTypeConfiguration<TEntity> where TEntity : BaseEntity
  6. {
  7. #region Utilities
  8. /// <summary>
  9. /// Developers can override this method in custom partial classes in order to add some custom configuration code
  10. /// </summary>
  11. /// <param name="builder">The builder to be used to configure the entity</param>
  12. protected virtual void PostConfigure(EntityTypeBuilder<TEntity> builder)
  13. {
  14. }
  15. #endregion
  16.  
  17. #region Methods
  18. /// <summary>
  19. /// Configures the entity
  20. /// </summary>
  21. /// <param name="builder">The builder to be used to configure the entity</param>
  22. public virtual void Configure(EntityTypeBuilder<TEntity> builder)
  23. {
  24. //add custom configuration
  25. this.PostConfigure(builder);
  26. }
  27.  
  28. /// <summary>
  29. /// Apply this mapping configuration
  30. /// </summary>
  31. /// <param name="modelBuilder">The builder being used to construct the model for the database context</param>
  32. public virtual void ApplyConfiguration(ModelBuilder modelBuilder)
  33. {
  34. modelBuilder.ApplyConfiguration(this);
  35. }
  36. #endregion
  37. }
  1. /// <summary>
  2. /// 表示基本EF对象上下文
  3. /// </summary>
  4. public partial class NopObjectContext : DbContext, IDbContext
  5. {
  6. #region 构造函数
  7. public NopObjectContext(DbContextOptions<NopObjectContext> options) : base(options)
  8. {
  9. }
  10. #endregion
  11.  
  12. #region 公共方法
  13. /// <summary>
  14. /// 进一步配置注册映射模型
  15. /// </summary>
  16. /// <param name="modelBuilder">用于为该上下文构造模型的构造器</param>
  17. protected override void OnModelCreating(ModelBuilder modelBuilder)
  18. {
  19. //动态加载所有实体和查询类型配置
  20. var typeConfigurations = Assembly.GetExecutingAssembly().GetTypes().Where(type =>
  21. (type.BaseType?.IsGenericType ?? false)
  22. && (type.BaseType.GetGenericTypeDefinition() == typeof(NopEntityTypeConfiguration<>)));
  23.  
  24. foreach (var typeConfiguration in typeConfigurations)
  25. {
  26. var configuration = (IMappingConfiguration)Activator.CreateInstance(typeConfiguration);
  27. configuration.ApplyConfiguration(modelBuilder);
  28. }
  29.  
  30. base.OnModelCreating(modelBuilder);
  31. }
  32.  
  33. /// <summary>
  34. /// 通过添加传递的参数来修改输入SQL查询
  35. /// </summary>
  36. /// <param name="sql">The raw SQL query</param>
  37. /// <param name="parameters">The values to be assigned to parameters</param>
  38. /// <returns>Modified raw SQL query</returns>
  39. protected virtual string CreateSqlWithParameters(string sql, params object[] parameters)
  40. {
  41. //add parameters to sql
  42. for (var i = ; i <= (parameters?.Length ?? ) - ; i++)
  43. {
  44. if (!(parameters[i] is DbParameter parameter))
  45. continue;
  46.  
  47. sql = $"{sql}{(i > 0 ? "," : string.Empty)} @{parameter.ParameterName}";
  48.  
  49. //whether parameter is output
  50. if (parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Output)
  51. sql = $"{sql} output";
  52. }
  53.  
  54. return sql;
  55. }
  56. #endregion
  57.  
  58. #region 方法
  59. /// <summary>
  60. /// 创建可用于查询和保存实体实例的DbSet
  61. /// </summary>
  62. /// <typeparam name="TEntity">Entity type</typeparam>
  63. /// <returns>A set for the given entity type</returns>
  64. public virtual new DbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
  65. {
  66. return base.Set<TEntity>();
  67. }
  68.  
  69. /// <summary>
  70. /// 生成一个脚本,为当前模型创建所有表
  71. /// </summary>
  72. /// <returns>A SQL script</returns>
  73. public virtual string GenerateCreateScript()
  74. {
  75. return this.Database.GenerateCreateScript();
  76. }
  77.  
  78. /// <summary>
  79. /// 基于原始SQL查询为查询类型创建LINQ查询
  80. /// </summary>
  81. /// <typeparam name="TQuery">Query type</typeparam>
  82. /// <param name="sql">The raw SQL query</param>
  83. /// <returns>An IQueryable representing the raw SQL query</returns>
  84. public virtual IQueryable<TQuery> QueryFromSql<TQuery>(string sql) where TQuery : class
  85. {
  86. return this.Query<TQuery>().FromSql(sql);
  87. }
  88.  
  89. /// <summary>
  90. ///基于原始SQL查询为实体创建LINQ查询
  91. /// </summary>
  92. /// <typeparam name="TEntity">Entity type</typeparam>
  93. /// <param name="sql">The raw SQL query</param>
  94. /// <param name="parameters">The values to be assigned to parameters</param>
  95. /// <returns>An IQueryable representing the raw SQL query</returns>
  96. public virtual IQueryable<TEntity> EntityFromSql<TEntity>(string sql, params object[] parameters) where TEntity : BaseEntity
  97. {
  98. return this.Set<TEntity>().FromSql(CreateSqlWithParameters(sql, parameters), parameters);
  99. }
  100.  
  101. /// <summary>
  102. /// 对数据库执行给定的SQL
  103. /// </summary>
  104. /// <param name="sql">The SQL to execute</param>
  105. /// <param name="doNotEnsureTransaction">true - the transaction creation is not ensured; false - the transaction creation is ensured.</param>
  106. /// <param name="timeout">The timeout to use for command. Note that the command timeout is distinct from the connection timeout, which is commonly set on the database connection string</param>
  107. /// <param name="parameters">Parameters to use with the SQL</param>
  108. /// <returns>The number of rows affected</returns>
  109. public virtual int ExecuteSqlCommand(RawSqlString sql, bool doNotEnsureTransaction = false, int? timeout = null, params object[] parameters)
  110. {
  111. //set specific command timeout
  112. var previousTimeout = this.Database.GetCommandTimeout();
  113. this.Database.SetCommandTimeout(timeout);
  114.  
  115. var result = ;
  116. if (!doNotEnsureTransaction)
  117. {
  118. //use with transaction
  119. using (var transaction = this.Database.BeginTransaction())
  120. {
  121. result = this.Database.ExecuteSqlCommand(sql, parameters);
  122. transaction.Commit();
  123. }
  124. }
  125. else
  126. result = this.Database.ExecuteSqlCommand(sql, parameters);
  127.  
  128. //return previous timeout back
  129. this.Database.SetCommandTimeout(previousTimeout);
  130.  
  131. return result;
  132. }
  133.  
  134. /// <summary>
  135. /// 从上下文中分离一个实体
  136. /// </summary>
  137. /// <typeparam name="TEntity">Entity type</typeparam>
  138. /// <param name="entity">Entity</param>
  139. public virtual void Detach<TEntity>(TEntity entity) where TEntity : BaseEntity
  140. {
  141. if (entity == null)
  142. throw new ArgumentNullException(nameof(entity));
  143.  
  144. var entityEntry = this.Entry(entity);
  145. if (entityEntry == null)
  146. return;
  147.  
  148. //set the entity is not being tracked by the context
  149. entityEntry.State = EntityState.Detached;
  150. }
  151. #endregion
  152. }

代码都是从nop开源项目出抠出来的

IOC+EF+Core项目搭建EF封装(一)的更多相关文章

  1. IOC+EF+Core项目搭建IOC注入及框架(二)

    配置ServiceCollection /// <summary> /// 表示IServiceCollection的扩展 /// </summary> public stat ...

  2. Asp.net Core + EF Core + Bootstrap搭建的MVC后台通用管理系统模板(跨平台版本)

    Asp.net Core + EF Core + Bootstrap搭建的MVC后台通用管理系统模板(跨平台版本) 原创 2016年07月22日 10:33:51 23125 6月随着.NET COR ...

  3. EF Core 快速上手——EF Core 入门

    EF Core 快速上手--EF Core 介绍 本章导航 从本书你能学到什么 对EF6.x 程序员的一些话 EF Core 概述 1.3.1 ORM框架的缺点 第一个EF Core应用   本文是对 ...

  4. ASP.NET CORE 项目搭建(2022 年 3 月版)

    ASP.NET CORE 项目搭建(2022 年 3 月版) 自读 沉淀了多年的技术积累,在 .NET FRAMEWORK 的框架下尝试造过自己的轮子. 摸索着闭门造过 基于 OWIN 服务后端. 摸 ...

  5. EF Core 快速上手——EF Core的三种主要关系类型

    系列文章 EF Core 快速上手--EF Core 入门 本节导航 三种数据库关系类型建模 Migration方式创建和习修改数据库 定义和创建应用DbContext 将复杂查询拆分为子查询   本 ...

  6. ASP.NET Core MVC+EF Core项目实战

    项目背景 本项目参考于<Pro Entity Framework Core 2 for ASP.NET Core MVC>一书,项目内容为party邀请答复. 新建项目 本项目开发工具为V ...

  7. EF Core 三 、 EF Core CRUD

    EF Core CRUD 上篇文章中,我们已经基本入门了EFCore,搭建了一个简单的EFCore项目,本文开始简单使用下EF,做增删改查的相关操作: 一.数据新增操作(C) public stati ...

  8. 《Asp.Net Core3 + Vue3入坑教程》-Net Core项目搭建与Swagger配置步骤

    简介 <Asp.Net Core3 + Vue3入坑教程> 此教程仅适合新手入门或者前后端分离尝试者.可以根据图文一步一步进操作编码也可以选择直接查看源码.每一篇文章都有对应的源码 教程后 ...

  9. EF Core 迁移过程遇到EF Core tools version版本不相符的解决方案

    如果你使用命令: PM> add-migration Inital 提示如下信息时: The EF Core tools version '2.1.1-rtm-30846' is older t ...

随机推荐

  1. Java实现RS485串口通信,发送和接收数据进行解析

    最近项目有一个空气检测仪,需要得到空气检测仪的实时数据,保存到数据库当中.根据了解得到,硬件是通过rs485进行串口通讯的,需要发送16进制命令给仪器,然后通过轮询来得到数据. 需要先要下载RXTX的 ...

  2. required string parameter 'XXX'is not present 的几种情况

    required string parameter 'XXX'is not present 的几种情况 情况一:原因是由于头文件类型不对,可以在MediaType中选择合适的类型,例如GET和POST ...

  3. go 指南学习笔记

    1   If  for 后面没有小括号.后面的花括号,要在当前行,并且中间有内容,右花括号要单独一行. 因为go会格式化代码,自动插入分号. 2 函数和方法的区别: 方法需要有一个接受者(select ...

  4. 【数值分析】Python实现Lagrange插值

    一直想把这几个插值公式用代码实现一下,今天闲着没事,尝试尝试. 先从最简单的拉格朗日插值开始!关于拉格朗日插值公式的基础知识就不赘述,百度上一搜一大堆. 基本思路是首先从文件读入给出的样本点,根据输入 ...

  5. 【CNN】--- 卷积过程中RGB与灰度的区别

    版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/hacker_Dem_br/article/ ...

  6. jmeter元件作用及执行顺序

    jmeter是一个开源的性能测试工具,它可以通过鼠标拖拽来随意改变元件之间的顺序以及元件的父子关系,那么随着它们的顺序和所在的域不同,它们在执行的时候,也会有很多不同. jmeter的test pla ...

  7. Microsoft SQL Server 2008 R2 安装遇到的问题

    SQL Server 安装过很多次了,第一次遇见这样的问题: TITLE: Microsoft SQL Server 2008 R2 安装程序----------------------------- ...

  8. String.format()详细用法

    String.format()字符串常规类型格式化的两种重载方式 format(String format, Object… args) 新字符串使用本地语言环境,制定字符串格式和参数生成格式化的新字 ...

  9. Activiti6 应用安装 activiti-admin,activiti-app,activiti-rest

    activiti6安装包中 1/直接将三个war包放入tomcat中,即可运行,使用H2内存数据库 2/使用mysql数据库运行 2.1/activiti-admin # security confi ...

  10. Python之内置装饰器property

    # -*- coding: utf-8 -*- # author:baoshan class Student(object): def __init__(self, name): self.name ...