EFCore CodeFirst模型迁移生成数据库备注(mysql)
重写Mysql下sql脚本生成器
using Framework.NetCore.Extensions;
using Framework.NetCore.Models;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations.Operations;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Framework.NetCore.EfDbContext
{
public class MyMigrationsSqlGenerator : MySqlMigrationsSqlGenerator
{
public MyMigrationsSqlGenerator(
MigrationsSqlGeneratorDependencies dependencies,
IMigrationsAnnotationProvider migrationsAnnotations,
IMySqlOptions mySqlOptions)
: base(dependencies, migrationsAnnotations, mySqlOptions)
{
}
protected override void Generate(MigrationOperation operation, IModel model, MigrationCommandListBuilder builder)
{
base.Generate(operation, model, builder);
if (operation is CreateTableOperation || operation is AlterTableOperation)
CreateTableComment(operation, model, builder);
if (operation is AddColumnOperation || operation is AlterColumnOperation)
CreateColumnComment(operation, model, builder);
}
/// <summary>
/// Create table comment.
/// </summary>
/// <param name="operation"></param>
/// <param name="builder"></param>
private void CreateTableComment(MigrationOperation operation, IModel model, MigrationCommandListBuilder builder)
{
string tableName = string.Empty;
string description = string.Empty;
if (operation is AlterTableOperation)
{
var t = operation as AlterColumnOperation;
tableName = (operation as AlterTableOperation).Name;
}
if (operation is CreateTableOperation)
{
var t = operation as CreateTableOperation;
var addColumnsOperation = t.Columns;
tableName = (operation as CreateTableOperation).Name;
foreach (var item in addColumnsOperation)
{
CreateColumnComment(item, model, builder);
}
}
description = DbDescriptionHelper.GetDescription(tableName);
if (tableName.IsNullOrWhiteSpace())
throw new Exception("Create table comment error.");
var sqlHelper = Dependencies.SqlGenerationHelper;
builder
.Append("ALTER TABLE ")
.Append(sqlHelper.DelimitIdentifier(tableName).ToLower())
.Append(" COMMENT ")
.Append("'")
.Append(description)
.Append("'")
.AppendLine(sqlHelper.StatementTerminator)
.EndCommand();
}
/// <summary>
/// Create column comment.
/// </summary>
/// <param name="operation"></param>
/// <param name="builder"></param>
private void CreateColumnComment(MigrationOperation operation, IModel model, MigrationCommandListBuilder builder)
{
//alter table a1log modify column UUID VARCHAR(26) comment '修改后的字段注释';
string tableName = string.Empty;
string columnName = string.Empty;
string columnType = string.Empty;
string description = string.Empty;
if (operation is AlterColumnOperation)
{
var t = (operation as AlterColumnOperation);
tableName = t.Table;
columnName = t.Name;
columnType = GetColumnType(t.Schema, t.Table, t.Name, t.ClrType, t.IsUnicode, t.MaxLength, t.IsFixedLength, t.IsRowVersion, model);
}
if (operation is AddColumnOperation)
{
var t = (operation as AddColumnOperation);
tableName = t.Table;
columnName = t.Name;
columnType = GetColumnType(t.Schema, t.Table, t.Name, t.ClrType, t.IsUnicode, t.MaxLength, t.IsFixedLength, t.IsRowVersion, model);
description = DbDescriptionHelper.GetDescription(tableName, columnName);
}
if (columnName.IsNullOrWhiteSpace() || tableName.IsNullOrWhiteSpace() || columnType.IsNullOrWhiteSpace())
throw new Exception("Create columnt comment error." + columnName + "/" + tableName + "/" + columnType);
var sqlHelper = Dependencies.SqlGenerationHelper;
builder
.Append("ALTER TABLE ")
.Append(sqlHelper.DelimitIdentifier(tableName).ToLower())
.Append(" MODIFY COLUMN ")
.Append(columnName)
.Append(" ")
.Append(columnType)
.Append(" COMMENT ")
.Append("'")
.Append(description)
.Append("'")
.AppendLine(sqlHelper.StatementTerminator)
.EndCommand();
}
}
public class DbDescriptionHelper
{
public static string b { get; set; } = "Framework.Website.Models";
public static string c { get; set; } = @"C:\Users\fxy75\Downloads\pos3.0\Framework.Website.Models";
public static List<DbDescription> list { get; set; }
public static string GetDescription(string table, string column = "")
{
if (list == null || list.Count() == 0)
{
list = GetDescription();
}
if (!string.IsNullOrWhiteSpace(table))
{
if (string.IsNullOrWhiteSpace(column))
{
var x = list.FirstOrDefault(p => p.Name == table);
if (x != null)
return x.Description;
return string.Empty;
}
else
{
var x = list.FirstOrDefault(p => p.Name == table);
if (x != null)
{
var y = x.Column;
if (y.IsNotNull())
{
var z = y.FirstOrDefault(p => p.Name == column);
if (z != null)
return z.Description;
}
}
return string.Empty;
}
}
else
return string.Empty;
}
public static List<DbDescription> GetDescription()
{
var d = new List<DbDescription>();
var e = Assembly.Load(b);
var f = e?.GetTypes();
var g = f?
.Where(t => t.IsClass
&& !t.IsGenericType
&& !t.IsAbstract
&& t.GetInterfaces().Any(m => m.GetGenericTypeDefinition() == typeof(IBaseModel<>))
).ToList();
foreach (var h in g)
{
var i = new DbDescription();
var j = c + "\\" + h.Name + ".cs";
var k = File.ReadAllText(j);
k = k.Substring(k.IndexOf("{") + 1, k.LastIndexOf("}") - k.IndexOf("{") - 1).Replace("\n", "");
var l = k.Substring(k.IndexOf(" {") + 2, k.LastIndexOf(" }") - k.IndexOf(" {") - 1).Replace("\n", "");
string[] slipt = { "}\r" };
var m = l.Split(slipt, StringSplitOptions.None).ToList();
var n = new List<DbDescription>();
foreach (var o in m)
{
var p = o.Replace("///", "");
var q = p.IndexOf("<summary>");
var r = p.LastIndexOf("</summary>");
var s = p.IndexOf("public");
var t = p.IndexOf("{");
var u = (q > 0 && r > 0) ? p.Substring(q + 9, r - q - 10).Replace("\r", "").Replace(" ", "") : "";
var v = (s > 0 && t > 0) ? p.Substring(s, t - s).Split(' ')[2] : "";
n.Add(new DbDescription()
{
Description = u,
Name = v
});
}
var w = k.Substring(0, k.IndexOf("{\r") - 1);
w = w.Replace("///", "");
var x = w.IndexOf("<summary>");
var y = w.LastIndexOf("</summary>");
var z = (x > 0 && y > 0) ? w.Substring(x + 9, y - x - 10).Replace("\r", "").Replace(" ", "") : "";
d.Add(new DbDescription()
{
Name = h.Name,
Description = z,
Column = n
});
}
return d;
}
}
public class DbDescription
{
public string Name { get; set; }
public string Description { get; set; }
public List<DbDescription> Column { get; set; }
}
}
EFCore DbContext中替换IMigrationsSqlGenerator
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseMySql(_option.ConnectionString)
.ReplaceService<IMigrationsSqlGenerator, MyMigrationsSqlGenerator>();
base.OnConfiguring(optionsBuilder);
}
EFCore CodeFirst模型迁移生成数据库备注(mysql)的更多相关文章
- 迁移应用数据库到MySQL Database on Azure
by Rong Yu 有用户问怎么把他们应用的数据库迁移到MySQL Database on Azure上,有哪些方式,有没有需要注意的地方.今天我们来概括介绍一下迁移应用数据库到MySQL Data ...
- Ubuntu 14.4 Django模型迁移到数据库提示 LookupError: unknown encoding: utf8mb4 解决方法
由于数据库中需要存储emoji表情,因此需要mysql支持utf8mb4,参考前面的文章升级数据库. 但是由于服务器上面的python-mysqldb连接包版本为1.2.3不支持utf8mb4,因此报 ...
- codefirst数据迁移技术,在保留数据库数据下实现对模型的修改并映射到数据库
一前言 这是我的处女作,写的不好的地方还望指出共同讨论.EF的数据访问方式有三种DbFirst,ModelFirst,还有本文要提到的CodeFirst 三者都是以ORM的方式建立.本人之前学习的.n ...
- EF CodeFirst关于Mysql如何自动生成数据库表
相对于sqlserver数据库,mysql的配置过程相对麻烦一些,我们从0讲起. 1.新建一个控制台应用程序 右键点击引用--管理NuGet程序包,搜索Mysql.Data.Entity并安装,安装完 ...
- EFCore CodeFirst 适配数据库
EF6中可以直接根据代码模型生成数据库Database.SetInitializer即可 在EFCore中如何实现呢? 这项功能放在了DatabaseFacade对象中,传入数据库上下文对象实例化到一 ...
- EF使用CodeFirst方式生成数据库&技巧经验
前言 EF已经发布很久了,也有越来越多的人在使用EF.如果你已经能够非常熟练的使用EF的功能,那么就不需要看了.本文意在将自己使用EF的方式记录下来备忘,也是为了给刚刚入门的同学一些指导.看完此文,你 ...
- EF架构~codeFirst从初始化到数据库迁移
一些介绍 CodeFirst是EntityFrameworks的一种开发模式,即代码优先,它以业务代码为主,通过代码来生成数据库,并且加上migration的强大数据表比对功能来生成数据库版本,让程序 ...
- Django:模型model和数据库mysql(一)
以一个栗子尝试来记录: 两个表存储在数据库中,BookInfo表示书,HeroInfo表示人物.一本书中有多个人物 在MySQL中新建一个数据库Django1,不用创建表,用Django模型来配置数据 ...
- "ApplicationDbContext"(泛指之类的数据库上下文模型)上下文的模型已在数据库创建后发生更改。请考虑使用 Code First 迁移更新数据库。
一,在我使用自动生成数据库的时候,当你改变了数据库就会出现下面问题 "ApplicationDbContext"(泛指之类的数据库上下文模型)上下文的模型已在数据库创建后发生更改. ...
随机推荐
- Expert Python programming - Reading Notes
1. MRO: method resolution order lookup order: L(MyClass) = [MyClass, merged(L(Base1), L(Base2), Base ...
- Web Scalability for Startup Engineers Tip&Techniques for Scaling You Web Application --读书笔记
Web Scalability for Startup Engineers Tip&Techniques for Scaling You Web Application 第1章和第2章讲述可伸 ...
- MySQL出现GROUP BY clause错误解决办法
#1)当mysql数据库出现如下错误:#which is not functionally dependent on columns in GROUP BY clause; this is incom ...
- springMVC 中 ajax get 请求和 post 请求的坑以及参数传递
1, ajax 请求 无论为 post ,或者 get ,url中带有?形式的参数,后台都能以String类型变量接收,变量名称和参数名称必须一致 前台ajax: $.ajax( "prod ...
- 解决activeandroid no such table
场景:activeandroid拷贝数据库 (1)复制sql数据库到项目的assets目录,例如/myapp/src/main/assets/prepop.db (2)确保manifest的AA_DB ...
- 在vue组件库中不能使用v-for
没事的,有点时候编辑器报错,但运行不一定出错, 在vue组件中注意template标签
- 线程锁(互斥锁Mutex)
线程锁(互斥锁Mutex) 一个进程下可以启动多个线程,多个线程共享父进程的内存空间,也就意味着每个线程可以访问同一份数据,此时,如果2个线程同时要修改同一份数据,会出现什么状况? # -*- cod ...
- 如何关闭OSX 10.11 SIP (System Integrity Protection)
http://www.jianshu.com/p/0572336a0771 注意:SIP功能是Apple在OSX上推出的系统完整性保护功能,对于普通MAC用户来说是一项安全保护功能,如果不了解他的作用 ...
- 项目中多条数据保存的json实例
//js代码function checkCode(num){ var typeid = $("#typeid").val(); if(typeid == "") ...
- Luogu P1782 旅行商的背包
题目传送门 卡常背包果然名不虚传 算法主体就是两种背包分开跑,先跑多重背包,再跑奇货 不知道为什么,这题二进制拆分好像要比单调队列优化快一些 然后这题毒瘤的地方就出来了: 如果一件物品的体积\(\ti ...