重写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. Metasploits之ms10_018

    漏洞详情:https://technet.microsoft.com/library/security/ms10-018 一准备: 1:kali Linux系统 192.168.195.129 2:W ...

  2. 《深入理解java虚拟机》笔记(1)运行时数据区域

    1.Java与C++之间有一堵由内存动态分配和垃圾收集技术所围成的“高墙”,墙外面的人想进去,墙里面的人却想出来. 2.运行时数据区域划分 java虚拟机在执行java程序的过程中会把它所管理的内存划 ...

  3. javaoo封装

  4. ps 进程管理

    一. 进程管理 1. pstree 2. ps 3. top 4. nice 5. free 6. screen 二. 程序与进程 程序是静态的文件,进程是动态运行的程序. 三. 进程和线程 一个程序 ...

  5. ios 自定义消息提示框

    自定义提示框,3秒钟后自动消失.如上图显示效果. 提示框加载代码: - (void)viewDidLoad { [super viewDidLoad]; //将view背景颜色变更为黄色 self.v ...

  6. git 设置了ssh key 还是需要输入账户和密码

    参考这篇文章https://blog.csdn.net/shahuhu000/article/details/86625987 git remote remove origingit remote a ...

  7. shell流程语句使用介绍

    1)使用if.case.read例子1:#!/bin/bash#读取终端输入的字符read -p "Please input a Number:" nn1=`echo $n|sed ...

  8. selenium-WebElement接口常用方法

    1.submit()方法用于提交表单. 例如:在收索框输入关键字之后的“回车”操作,就可以通过submit()方法模拟. 例如: from selenium import webdriverdrive ...

  9. asp.net core mvc 异步表单(Ajax.BeginForm)

    .net core中已经没有beginform扩展函数了. 通过Bower引入jquery-ajax-unobtrusive: <script src="~/lib/jquery-aj ...

  10. Java异常处理:如何写出“正确”但被编译器认为有语法错误的程序

    文章的标题看似自相矛盾,然而我在"正确"二字上打了引号.我们来看一个例子,关于Java异常处理(Exception Handling)的一些知识点. 看下面这段程序.方法pleas ...