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"(泛指之类的数据库上下文模型)上下文的模型已在数据库创建后发生更改. ...
随机推荐
- c#中的特性
c#中的特性 特性在我的理解就是在类或者方法或者参数上加上指定的标记,然后实现指定的效果. 和Java中的注解@Annotation类似. c#内置的特性之Obsolete [Obsolete(&qu ...
- 在spring的过滤器中注入实体类(@autowire会失效可使用这个方法)
转载:难得可贵的好文章 https://blog.csdn.net/chl191623691/article/details/78657638 首先,本文 绝对是好文!不止本文,作者的文章都是很经 ...
- Apache的多处理模块MPM
本博文主要参数 Apache 2.2文档以及Apache模块开发指南 Apache的整个运行可以分为两个阶段:启动阶段和运行阶段. 在启动阶段时,它以ROOT特权来启动,进行解析配置文件(一般就是ht ...
- 对shell的简单认识
shell是一个命令解释器: shell分为交互式shell和非交互式shell: 交互式shell就是命令行一问一答:非交互式shell是像shell文本那样,一次解析文本, 并未在命令行给我们作出 ...
- CF1062D Fun with Integers
思路: 找规律. 实现: #include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { ...
- iOS(iPhone,iPad))开发(Objective-C)开发库常用库索引
http://www.code4app.com 这网站不错,收集各种 iOS App 开发可以用到的代码示例 http://www.cocoacontrols.com/ 英文版本的lib收集 ht ...
- 快学UiAutomator创建第一个实例
工具准备 一.准备好java环境(JDK)和安卓环境(SDK.ADT)jdk1.6+ \eclipse\SDK \ADT详情百度,安装java环境 二.打开eclipse 三.创建步骤: 右键新建== ...
- C01 C语言基础
目录 C语言简史及特点 C语言开发环境 C语言程序结构 C语言基本输入输出函数 编译 软件类型 C语言简要及特点 什么是计算机语言 计算机语言是用于人与计算机之间通讯的语言. 计算机遵照接收到的计算机 ...
- hibernate的注解
1.many-to-one @ManyToOne @JoinColumn(name = "user_id") 2.many-to-many /** * 双向关联关系中,有且仅有一端 ...
- 设置section的距离
在ios7中使用group类型的tableview时,第一个section距离navigationbar的距离很大,不符合这边的设计图.使用 myTableView . sectionHeaderHe ...