重写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)的更多相关文章

  1. 迁移应用数据库到MySQL Database on Azure

    by Rong Yu 有用户问怎么把他们应用的数据库迁移到MySQL Database on Azure上,有哪些方式,有没有需要注意的地方.今天我们来概括介绍一下迁移应用数据库到MySQL Data ...

  2. Ubuntu 14.4 Django模型迁移到数据库提示 LookupError: unknown encoding: utf8mb4 解决方法

    由于数据库中需要存储emoji表情,因此需要mysql支持utf8mb4,参考前面的文章升级数据库. 但是由于服务器上面的python-mysqldb连接包版本为1.2.3不支持utf8mb4,因此报 ...

  3. codefirst数据迁移技术,在保留数据库数据下实现对模型的修改并映射到数据库

    一前言 这是我的处女作,写的不好的地方还望指出共同讨论.EF的数据访问方式有三种DbFirst,ModelFirst,还有本文要提到的CodeFirst 三者都是以ORM的方式建立.本人之前学习的.n ...

  4. EF CodeFirst关于Mysql如何自动生成数据库表

    相对于sqlserver数据库,mysql的配置过程相对麻烦一些,我们从0讲起. 1.新建一个控制台应用程序 右键点击引用--管理NuGet程序包,搜索Mysql.Data.Entity并安装,安装完 ...

  5. EFCore CodeFirst 适配数据库

    EF6中可以直接根据代码模型生成数据库Database.SetInitializer即可 在EFCore中如何实现呢? 这项功能放在了DatabaseFacade对象中,传入数据库上下文对象实例化到一 ...

  6. EF使用CodeFirst方式生成数据库&技巧经验

    前言 EF已经发布很久了,也有越来越多的人在使用EF.如果你已经能够非常熟练的使用EF的功能,那么就不需要看了.本文意在将自己使用EF的方式记录下来备忘,也是为了给刚刚入门的同学一些指导.看完此文,你 ...

  7. EF架构~codeFirst从初始化到数据库迁移

    一些介绍 CodeFirst是EntityFrameworks的一种开发模式,即代码优先,它以业务代码为主,通过代码来生成数据库,并且加上migration的强大数据表比对功能来生成数据库版本,让程序 ...

  8. Django:模型model和数据库mysql(一)

    以一个栗子尝试来记录: 两个表存储在数据库中,BookInfo表示书,HeroInfo表示人物.一本书中有多个人物 在MySQL中新建一个数据库Django1,不用创建表,用Django模型来配置数据 ...

  9. "ApplicationDbContext"(泛指之类的数据库上下文模型)上下文的模型已在数据库创建后发生更改。请考虑使用 Code First 迁移更新数据库。

    一,在我使用自动生成数据库的时候,当你改变了数据库就会出现下面问题 "ApplicationDbContext"(泛指之类的数据库上下文模型)上下文的模型已在数据库创建后发生更改. ...

随机推荐

  1. Java中try catch finally语句中含有return语句的执行情况

    finally块中的内容会先于try中的return语句执行,如果finall语句块中也有return语句的话,那么直接从finally中返回了,这也是不建议在finally中return的原因.下面 ...

  2. 剑指offer部分编程题

    一 斐波那契数列 题目描述: 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项. n<=39 问题分析: 可以肯定的是这一题通过递归的方式是肯定能做出来,但是这样会有 ...

  3. JS的文本框验证以及form表单的提交阻止

    js: 1.只能输入数字 只能输入数字:<input type="text" onkeyup="javascript:ReNumber(this)" /& ...

  4. webApi Authentication failed because the remote party has closed the transport stream\身份验证失败了,因为远程方关闭了传输流。

    public class CertificateTrust { public static void SetCertificatePolicy() { //当在浏览器中可以正常访问,而code中出现错 ...

  5. Java中的变量——通过示例学习Java编程(4)

    作者:CHAITANYA SINGH 来源:https://www.koofun.com/pro/kfpostsdetail?kfpostsid=14&cid= 变量是用来存放可以更改的值的容 ...

  6. Spring MVC 入门实例报错404的解决方案

    若启动服务器控制台报错,并且是未找到xml配置文件,初始化DispatchServlet失败,或者控制台未报错404,那么: 1.URL的排查: 格式-----------协议名://地址:端口号/上 ...

  7. redis和memcache

    redis安装:($sudo apt-get update,$sudo apt-get install redis-server) redis启动:($redis-server): 查看redis是否 ...

  8. 在Window上用cmd创建.htaccess文件

    Windows 图形下不能直接建立空名字的文件,所以没法直接创建.htaccess文件,不过可以通过命令行创建: cd /path/to/your/dir/ type nul>.htaccess ...

  9. cf559C. Gerald and Giant Chess(容斥原理)

    题意 $h \times w$的网格,有$n$个障碍点, 每次可以向右或向下移动 求从$(1, 1)$到$(h, w)$不经过障碍点的方案数 Sol 容斥原理 从$(1, 1)$到$(h, w)$不经 ...

  10. JavaScript之执行环境及作用域

        执行环境定义了变量或函数有权访问的其他数据,决定了它们各自的行为.每个执行环境都有一个与之关联的变量对象,环境中定义的所有变量和函数都保存在这个对象中.我们编写的代码是无法访问这个对象的,但解 ...