SqlServer CodeFirst 适配完成(同步结构)

This commit is contained in:
28810 2018-12-19 12:06:04 +08:00
parent 7bfe4efb2c
commit df07b7bcc4
9 changed files with 153 additions and 48 deletions

View File

@ -1,18 +1,10 @@
# CodeFirst # CodeFirst
### 支持的类型 | 数据库 | 支持的类型类型 |
| - | - |
| MySql | bool, sbyte, short, int, long, byte, ushort, uint, ulong, double, float, decimal, Guid, TimeSpan, DateTime<br>bool?, sbyte?, short?, int?, long?, byte?, ushort?, uint?, ulong?, double?, float?, decimal?, Guid?, TimeSpan?, DateTime?<br>byte[], string, Enum & FlagsEnum<br>MygisPoint, MygisLineString, MygisPolygon, MygisMultiPoint, MygisMultiLineString, MygisMultiPolygon |
| SqlServer | bool, sbyte, short, int, long, byte, ushort, uint, ulong, double, float, decimal, Guid, TimeSpan, DateTime, DateTimeOffset<br>bool?, sbyte?, short?, int?, long?, byte?, ushort?, uint?, ulong?, double?, float?, decimal?, Guid?, TimeSpan?, DateTime?, DateTimeOffset?<br>byte[], string, Enum & FlagsEnum |
bool, byte, short, int, long, byte, ushort, uint, ulong, double, float, decimal, int, Guid
bool?, byte?, short?, int?, long?, byte?, ushort?, uint?, ulong?, double?, float?, decimal?, int?, Guid?
TimeSpan, DateTime
TimeSpan?, DateTime?
byte[], string
MygisPoint, MygisLineString, MygisPolygon, MygisMultiPoint, MygisMultiLineString, MygisMultiPolygon
```csharp ```csharp
IFreeSql fsql = new FreeSql.FreeSqlBuilder() IFreeSql fsql = new FreeSql.FreeSqlBuilder()

View File

@ -21,7 +21,7 @@ namespace FreeSql.Tests.Generator {
[Fact] [Fact]
public void BuildRichEntityNavigationObject() { public void BuildRichEntityNavigationObject() {
var gen = new TemplateGenerator(); var gen = new TemplateGenerator();
gen.Build(g.mysql.DbFirst, @"C:\Users\28810\Desktop\github\FreeSql\Templates\MySql\rich-entity-navigation-object", @"C:\Users\28810\Desktop\新建文件夹 (9)", "cccddd"); gen.Build(g.mysql.DbFirst, @"C:\Users\28810\Desktop\github\FreeSql\Templates\MySql\rich-entity-navigation-object", @"C:\Users\28810\Desktop\新建文件夹 (9)", "ManagerDB");
} }
} }
} }

View File

@ -0,0 +1,70 @@
using FreeSql.DataAnnotations;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.SqlServer {
public class SqlServerCodeFirstTest {
[Fact]
public void GetComparisonDDLStatements() {
var sql = g.sqlserver.CodeFirst.GetComparisonDDLStatements<TableAllType>();
}
[Table(Name = "tb_alltype")]
class TableAllType {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
[Column(OldName = "testFieldBool1111")]
public bool testFieldBool { get; set; }
public sbyte testFieldSByte { get; set; }
public short testFieldShort { get; set; }
public int testFieldInt { get; set; }
public long testFieldLong { get; set; }
public byte testFieldByte { get; set; }
public ushort testFieldUShort { get; set; }
public uint testFieldUInt { get; set; }
public ulong testFieldULong { get; set; }
public double testFieldDouble { get; set; }
public float testFieldFloat { get; set; }
public decimal testFieldDecimal { get; set; }
public TimeSpan testFieldTimeSpan { get; set; }
public DateTime testFieldDateTime { get; set; }
public DateTimeOffset testFieldDateTimeOffset { get; set; }
public byte[] testFieldBytes { get; set; }
public string testFieldString { get; set; }
public Guid testFieldGuid { get; set; }
public bool? testFieldBoolNullable { get; set; }
public sbyte? testFieldSByteNullable { get; set; }
public short? testFieldShortNullable { get; set; }
public int? testFieldIntNullable { get; set; }
public long? testFielLongNullable { get; set; }
public byte? testFieldByteNullable { get; set; }
public ushort? testFieldUShortNullable { get; set; }
public uint? testFieldUIntNullable { get; set; }
public ulong? testFieldULongNullable { get; set; }
public double? testFieldDoubleNullable { get; set; }
public float? testFieldFloatNullable { get; set; }
public decimal? testFieldDecimalNullable { get; set; }
public TimeSpan? testFieldTimeSpanNullable { get; set; }
public DateTime? testFieldDateTimeNullable { get; set; }
public DateTimeOffset? testFieldDateTimeNullableOffset { get; set; }
public Guid? testFieldGuidNullable { get; set; }
public TableAllTypeEnumType1 testFieldEnum1 { get; set; }
public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; }
public TableAllTypeEnumType2 testFieldEnum2 { get; set; }
public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; }
}
public enum TableAllTypeEnumType1 { e1, e2, e3, e5 }
[Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 }
}
}

View File

@ -6,7 +6,8 @@ using System.Text;
public class g { public class g {
public static IFreeSql mysql = new FreeSql.FreeSqlBuilder() public static IFreeSql mysql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10") //.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10")
.UseConnectionString(FreeSql.DataType.MySql, "Data Source=123.207.16.102;Port=3306;User ID=root;Password=qwe369258/*-;Initial Catalog=ManagerDB;Charset=utf8;SslMode=none;Max pool size=10")
.Build(); .Build();
public static IFreeSql sqlserver = new FreeSql.FreeSqlBuilder() public static IFreeSql sqlserver = new FreeSql.FreeSqlBuilder()

View File

@ -358,6 +358,16 @@ where a.constraint_schema in ({1}) and a.table_name in ({0}) and not isnull(posi
if (ret == 0) ret = t1.Name.CompareTo(t2.Name); if (ret == 0) ret = t1.Name.CompareTo(t2.Name);
return ret; return ret;
}); });
foreach(var loc4 in loc1) {
var dicUniques = new Dictionary<string, List<DbColumnInfo>>();
dicUniques.Add(string.Join(",", loc4.Primarys.Select(a => a.Name)), loc4.Primarys);
foreach(var loc5 in loc4.Uniques) {
var dickey = string.Join(",", loc5.Select(a => a.Name));
if (dicUniques.ContainsKey(dickey)) continue;
dicUniques.Add(dickey, loc5);
}
loc4.Uniques = dicUniques.Values.ToList();
}
loc2.Clear(); loc2.Clear();
loc3.Clear(); loc3.Clear();

View File

@ -357,6 +357,16 @@ where a.constraint_schema in ({1}) and a.table_name in ({0}) and not isnull(posi
if (ret == 0) ret = t1.Name.CompareTo(t2.Name); if (ret == 0) ret = t1.Name.CompareTo(t2.Name);
return ret; return ret;
}); });
foreach (var loc4 in loc1) {
var dicUniques = new Dictionary<string, List<DbColumnInfo>>();
dicUniques.Add(string.Join(",", loc4.Primarys.Select(a => a.Name)), loc4.Primarys);
foreach (var loc5 in loc4.Uniques) {
var dickey = string.Join(",", loc5.Select(a => a.Name));
if (dicUniques.ContainsKey(dickey)) continue;
dicUniques.Add(dickey, loc5);
}
loc4.Uniques = dicUniques.Values.ToList();
}
loc2.Clear(); loc2.Clear();
loc3.Clear(); loc3.Clear();

View File

@ -22,40 +22,51 @@ namespace FreeSql.SqlServer {
public bool IsAutoSyncStructure { get; set; } = true; public bool IsAutoSyncStructure { get; set; } = true;
static readonly Dictionary<string, (SqlDbType type, string dbtype, string dbtypeFull, bool? isUnsigned, bool? isnullable)> _dicCsToDb = new Dictionary<string, (SqlDbType type, string dbtype, string dbtypeFull, bool? isUnsigned, bool? isnullable)>() { static object _dicCsToDbLock = new object();
{ "System.Boolean", (SqlDbType.Bit, "bit","bit NOT NULL", null, false) },{ "System.Nullable`1[System.Boolean]", (SqlDbType.Bit, "bit","bit", null, true) }, static Dictionary<string, (SqlDbType type, string dbtype, string dbtypeFull, bool? isUnsigned, bool? isnullable)> _dicCsToDb = new Dictionary<string, (SqlDbType type, string dbtype, string dbtypeFull, bool? isUnsigned, bool? isnullable)>() {
{ typeof(bool).FullName, (SqlDbType.Bit, "bit","bit NOT NULL", null, false) },{ typeof(bool?).FullName, (SqlDbType.Bit, "bit","bit", null, true) },
{ "System.SByte", (SqlDbType.TinyInt, "tinyint", "tinyint NOT NULL", false, false) },{ "System.Nullable`1[System.SByte]", (SqlDbType.TinyInt, "tinyint", "tinyint", false, true) }, { typeof(sbyte).FullName, (SqlDbType.TinyInt, "tinyint", "tinyint NOT NULL", false, false) },{ typeof(sbyte?).FullName, (SqlDbType.TinyInt, "tinyint", "tinyint", false, true) },
{ "System.Int16", (SqlDbType.SmallInt, "smallint","smallint NOT NULL", false, false) },{ "System.Nullable`1[System.Int16]", (SqlDbType.SmallInt, "smallint", "smallint", false, true) }, { typeof(short).FullName, (SqlDbType.SmallInt, "smallint","smallint NOT NULL", false, false) },{ typeof(short?).FullName, (SqlDbType.SmallInt, "smallint", "smallint", false, true) },
{ "System.Int32", (SqlDbType.Int, "int", "int NOT NULL", false, false) },{ "System.Nullable`1[System.Int32]", (SqlDbType.Int, "int", "int", false, true) }, { typeof(int).FullName, (SqlDbType.Int, "int", "int NOT NULL", false, false) },{ typeof(int?).FullName, (SqlDbType.Int, "int", "int", false, true) },
{ "System.Int64", (SqlDbType.BigInt, "bigint","bigint NOT NULL", false, false) },{ "System.Nullable`1[System.Int64]", (SqlDbType.BigInt, "bigint","bigint", false, true) }, { typeof(long).FullName, (SqlDbType.BigInt, "bigint","bigint NOT NULL", false, false) },{ typeof(long?).FullName, (SqlDbType.BigInt, "bigint","bigint", false, true) },
{ "System.Byte", (SqlDbType.TinyInt, "tinyint","tinyint NOT NULL", true, false) },{ "System.Nullable`1[System.Byte]", (SqlDbType.TinyInt, "tinyint","tinyint", true, true) }, { typeof(byte).FullName, (SqlDbType.TinyInt, "tinyint","tinyint NOT NULL", true, false) },{ typeof(byte?).FullName, (SqlDbType.TinyInt, "tinyint","tinyint", true, true) },
{ "System.UInt16", (SqlDbType.SmallInt, "smallint","smallint NOT NULL", true, false) },{ "System.Nullable`1[System.UInt16]", (SqlDbType.SmallInt, "smallint", "smallint", true, true) }, { typeof(ushort).FullName, (SqlDbType.SmallInt, "smallint","smallint NOT NULL", true, false) },{ typeof(ushort?).FullName, (SqlDbType.SmallInt, "smallint", "smallint", true, true) },
{ "System.UInt32", (SqlDbType.Int, "int", "int NOT NULL", true, false) },{ "System.Nullable`1[System.UInt32]", (SqlDbType.Int, "int", "int", true, true) }, { typeof(uint).FullName, (SqlDbType.Int, "int", "int NOT NULL", true, false) },{ typeof(uint?).FullName, (SqlDbType.Int, "int", "int", true, true) },
{ "System.UInt64", (SqlDbType.BigInt, "bigint", "bigint NOT NULL", true, false) },{ "System.Nullable`1[System.UInt64]", (SqlDbType.BigInt, "bigint", "bigint", true, true) }, { typeof(ulong).FullName, (SqlDbType.BigInt, "bigint", "bigint NOT NULL", true, false) },{ typeof(ulong?).FullName, (SqlDbType.BigInt, "bigint", "bigint", true, true) },
{ "System.Double", (SqlDbType.Float, "double", "double NOT NULL", false, false) },{ "System.Nullable`1[System.Double]", (SqlDbType.Float, "double", "double", false, true) }, { typeof(double).FullName, (SqlDbType.Float, "float", "float NOT NULL", false, false) },{ typeof(double?).FullName, (SqlDbType.Float, "float", "float", false, true) },
{ "System.Single", (SqlDbType.Real, "float","float NOT NULL", false, false) },{ "System.Nullable`1[System.Single]", (SqlDbType.Real, "float","float", false, true) }, { typeof(float).FullName, (SqlDbType.Real, "real","real NOT NULL", false, false) },{ typeof(float?).FullName, (SqlDbType.Real, "real","real", false, true) },
{ "System.Decimal", (SqlDbType.Decimal, "decimal", "decimal(10,2) NOT NULL", false, false) },{ "System.Nullable`1[System.Decimal]", (SqlDbType.Decimal, "decimal", "decimal(10,2)", false, true) }, { typeof(decimal).FullName, (SqlDbType.Decimal, "decimal", "decimal(10,2) NOT NULL", false, false) },{ typeof(decimal?).FullName, (SqlDbType.Decimal, "decimal", "decimal(10,2)", false, true) },
{ "System.TimeSpan", (SqlDbType.Time, "time","time NOT NULL", false, false) },{ "System.Nullable`1[System.TimeSpan]", (SqlDbType.Time, "time", "time",false, true) }, { typeof(TimeSpan).FullName, (SqlDbType.Time, "time","time NOT NULL", false, false) },{ typeof(TimeSpan?).FullName, (SqlDbType.Time, "time", "time",false, true) },
{ "System.DateTime", (SqlDbType.DateTime, "datetime", "datetime NOT NULL", false, false) },{ "System.Nullable`1[System.DateTime]", (SqlDbType.DateTime, "datetime", "datetime", false, true) }, { typeof(DateTime).FullName, (SqlDbType.DateTime, "datetime", "datetime NOT NULL", false, false) },{ typeof(DateTime?).FullName, (SqlDbType.DateTime, "datetime", "datetime", false, true) },
{ "System.DateTimeOffset", (SqlDbType.DateTimeOffset, "datetimeoffset", "datetimeoffset NOT NULL", false, false) },{ "System.Nullable`1[System.DateTime]", (SqlDbType.DateTimeOffset, "datetimeoffset", "datetimeoffset", false, true) }, { typeof(DateTimeOffset).FullName, (SqlDbType.DateTimeOffset, "datetimeoffset", "datetimeoffset NOT NULL", false, false) },{ typeof(DateTimeOffset?).FullName, (SqlDbType.DateTimeOffset, "datetimeoffset", "datetimeoffset", false, true) },
{ "System.Byte[]", (SqlDbType.VarBinary, "varbinary", "varbinary(255)", false, null) }, { typeof(byte[]).FullName, (SqlDbType.VarBinary, "varbinary", "varbinary(255)", false, null) },
{ "System.String", (SqlDbType.NVarChar, "nvarchar", "nvarchar(255)", false, null) }, { typeof(string).FullName, (SqlDbType.NVarChar, "nvarchar", "nvarchar(255)", false, null) },
{ "System.Guid", (SqlDbType.UniqueIdentifier, "uniqueidentifier", "uniqueidentifier", false, false) },{ "System.Guid", (SqlDbType.UniqueIdentifier, "uniqueidentifier", "uniqueidentifier", false, true) }, { typeof(Guid).FullName, (SqlDbType.UniqueIdentifier, "uniqueidentifier", "uniqueidentifier NOT NULL", false, false) },{ typeof(Guid?).FullName, (SqlDbType.UniqueIdentifier, "uniqueidentifier", "uniqueidentifier", false, true) },
}; };
public (int type, string dbtype, string dbtypeFull, bool? isnullable)? GetDbInfo(Type type) { public (int type, string dbtype, string dbtypeFull, bool? isnullable)? GetDbInfo(Type type) {
if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return new (int, string, string, bool?)?(((int)trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable));
var enumType = type.IsEnum ? type : null; var enumType = type.IsEnum ? type : null;
if (enumType == null && type.FullName.StartsWith("System.Nullable`1[") && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First(); if (enumType == null && type.FullName.StartsWith("System.Nullable`1[") && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First();
if (enumType != null) { if (enumType != null) {
return ((int)SqlDbType.Int, "int", "int", type.IsEnum ? false : true); var newItem = enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any() ?
(SqlDbType.BigInt, "bigint", $"bigint{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true) :
(SqlDbType.Int, "int", $"int{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true);
if (_dicCsToDb.ContainsKey(type.FullName) == false) {
lock (_dicCsToDbLock) {
if (_dicCsToDb.ContainsKey(type.FullName) == false)
_dicCsToDb.Add(type.FullName, newItem);
}
}
return ((int)newItem.Item1, newItem.Item2, newItem.Item3, newItem.Item5);
} }
return _dicCsToDb.TryGetValue(type.FullName, out var trydc) ? new (int, string, string, bool?)?(((int)trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable)) : null; return null;
} }
public string GetComparisonDDLStatements<TEntity>() => this.GetComparisonDDLStatements(typeof(TEntity)); public string GetComparisonDDLStatements<TEntity>() => this.GetComparisonDDLStatements(typeof(TEntity));
@ -70,11 +81,11 @@ namespace FreeSql.SqlServer {
var isRenameTable = false; var isRenameTable = false;
var tbname = tb.DbName.Split(new[] { '.' }, 2); var tbname = tb.DbName.Split(new[] { '.' }, 2);
if (tbname.Length == 1) tbname = new[] { "dbo", tbname[0] }; if (tbname.Length == 1) tbname = new[] { "dbo", tbname[0] };
if (_orm.Ado.ExecuteScalar(CommandType.Text, "select 1 from dbo.sysobjects where id = object_id(N'[{0}].[{1}]') and OBJECTPROPERTY(id, N'IsUserTable')".FormatMySql(tbname)) == null) { //表不存在 if (_orm.Ado.ExecuteScalar(CommandType.Text, string.Format("select 1 from dbo.sysobjects where id = object_id(N'[{0}].[{1}]') and OBJECTPROPERTY(id, N'IsUserTable') = 1", tbname)) == null) { //表不存在
if (tboldname != null && _orm.Ado.ExecuteScalar(CommandType.Text, "select 1 from dbo.sysobjects where id = object_id(N'[{0}].[{1}]') and OBJECTPROPERTY(id, N'IsUserTable')".FormatMySql(tboldname)) != null) { //旧表存在 if (tboldname != null && _orm.Ado.ExecuteScalar(CommandType.Text, string.Format("select 1 from dbo.sysobjects where id = object_id(N'[{0}].[{1}]') and OBJECTPROPERTY(id, N'IsUserTable') = 1", tboldname)) != null) { //旧表存在
//修改表名 //修改表名
sb.Append(_commonUtils.FormatSql("EXEC sp_rename {0}, {1} GO \r\n", _commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}"), _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}"))); sb.Append(_commonUtils.FormatSql("EXEC sp_rename {0}, {1} \r\nGO \r\n", _commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}"), _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")));
isRenameTable = true; isRenameTable = true;
} else { } else {
@ -87,7 +98,7 @@ namespace FreeSql.SqlServer {
if (tbcol.Attribute.IsPrimary) sb.Append(" primary key"); if (tbcol.Attribute.IsPrimary) sb.Append(" primary key");
sb.Append(","); sb.Append(",");
} }
sb.Remove(sb.Length - 1, 1).Append("\r\n) GO \r\n"); sb.Remove(sb.Length - 1, 1).Append("\r\n) \r\nGO \r\n");
continue; continue;
} }
} }
@ -96,7 +107,7 @@ namespace FreeSql.SqlServer {
foreach (var tbcol in tb.Columns) addcols.Add(tbcol.Value.Attribute.Name, tbcol.Value); foreach (var tbcol in tb.Columns) addcols.Add(tbcol.Value.Attribute.Name, tbcol.Value);
var surplus = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase); var surplus = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase);
var dbcols = new List<DbColumnInfo>(); var dbcols = new List<DbColumnInfo>();
var sql = @"select var sql = string.Format(@"select
a.name 'Column' a.name 'Column'
,b.name + case ,b.name + case
when b.name in ('Char', 'VarChar', 'NChar', 'NVarChar', 'Binary', 'VarBinary') then '(' + when b.name in ('Char', 'VarChar', 'NChar', 'NVarChar', 'Binary', 'VarBinary') then '(' +
@ -105,14 +116,14 @@ a.name 'Column'
else cast(a.max_length as varchar) end + ')' else cast(a.max_length as varchar) end + ')'
when b.name in ('Numeric', 'Decimal') then '(' + cast(a.precision as varchar) + ',' + cast(a.scale as varchar) + ')' when b.name in ('Numeric', 'Decimal') then '(' + cast(a.precision as varchar) + ',' + cast(a.scale as varchar) + ')'
else '' end as 'SqlType' else '' end as 'SqlType'
,a.is_nullable 'IsNullable' ,case when a.is_nullable = 1 then '1' else '0' end 'IsNullable'
,a.is_identity 'IsIdentity' ,case when a.is_identity = 1 then '1' else '0' end 'IsIdentity'
from sys.columns a from sys.columns a
inner join sys.types b on b.user_type_id = a.user_type_id inner join sys.types b on b.user_type_id = a.user_type_id
left join sys.extended_properties AS c ON c.major_id = a.object_id AND c.minor_id = a.column_id left join sys.extended_properties AS c ON c.major_id = a.object_id AND c.minor_id = a.column_id
left join sys.tables d on d.object_id = a.object_id left join sys.tables d on d.object_id = a.object_id
left join sys.schemas e on e.schema_id = d.schema_id left join sys.schemas e on e.schema_id = d.schema_id
where a.object_id in (object_id(N'[{0}].[{1}]'))".FormatMySql(isRenameTable ? tboldname : tbname); where a.object_id in (object_id(N'[{0}].[{1}]'))", isRenameTable ? tboldname : tbname);
var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
foreach (var row in ds) { foreach (var row in ds) {
string column = string.Concat(row[0]); string column = string.Concat(row[0]);
@ -126,7 +137,7 @@ where a.object_id in (object_id(N'[{0}].[{1}]'))".FormatMySql(isRenameTable ? tb
trycol.Attribute.IsIdentity != is_identity) { trycol.Attribute.IsIdentity != is_identity) {
sb.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ALTER COLUMN ").Append(_commonUtils.QuoteSqlName(column)).Append(" ").Append(trycol.Attribute.DbType.ToUpper()); sb.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ALTER COLUMN ").Append(_commonUtils.QuoteSqlName(column)).Append(" ").Append(trycol.Attribute.DbType.ToUpper());
if (trycol.Attribute.IsIdentity && trycol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" identity(1,1)"); if (trycol.Attribute.IsIdentity && trycol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" identity(1,1)");
sb.Append(" GO \r\n"); sb.Append(" \r\nGO \r\n");
} }
addcols.Remove(column); addcols.Remove(column);
} else } else
@ -134,15 +145,15 @@ where a.object_id in (object_id(N'[{0}].[{1}]'))".FormatMySql(isRenameTable ? tb
} }
foreach (var addcol in addcols.Values) { foreach (var addcol in addcols.Values) {
if (string.IsNullOrEmpty(addcol.Attribute.OldName) == false && surplus.ContainsKey(addcol.Attribute.OldName)) { //修改列名 if (string.IsNullOrEmpty(addcol.Attribute.OldName) == false && surplus.ContainsKey(addcol.Attribute.OldName)) { //修改列名
sb.Append(_commonUtils.FormatSql("EXEC sp_rename {0}, {1}, 'COLUMN' GO \r\n", _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{addcol.Attribute.OldName}"), _commonUtils.QuoteSqlName(addcol.Attribute.Name))); sb.Append(_commonUtils.FormatSql("EXEC sp_rename {0}, {1}, 'COLUMN' \r\nGO \r\n", $"{tbname[0]}.{tbname[1]}.{addcol.Attribute.OldName}", addcol.Attribute.Name));
sb.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ALTER COLUMN ").Append(_commonUtils.QuoteSqlName(addcol.Attribute.Name)).Append(" ").Append(addcol.Attribute.DbType.ToUpper()); sb.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ALTER COLUMN ").Append(_commonUtils.QuoteSqlName(addcol.Attribute.Name)).Append(" ").Append(addcol.Attribute.DbType.ToUpper());
if (addcol.Attribute.IsIdentity && addcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" identity(1,1)"); if (addcol.Attribute.IsIdentity && addcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" identity(1,1)");
sb.Append(" GO \r\n"); sb.Append(" \r\nGO \r\n");
} else { //添加列 } else { //添加列
sb.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD ").Append(_commonUtils.QuoteSqlName(addcol.Attribute.Name)).Append(" ").Append(addcol.Attribute.DbType.ToUpper()); sb.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD ").Append(_commonUtils.QuoteSqlName(addcol.Attribute.Name)).Append(" ").Append(addcol.Attribute.DbType.ToUpper());
if (addcol.Attribute.IsIdentity && addcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" identity(1,1)"); if (addcol.Attribute.IsIdentity && addcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" identity(1,1)");
sb.Append(" GO \r\n"); sb.Append(" \r\nGO \r\n");
} }
} }
} }

View File

@ -374,6 +374,16 @@ where b.object_id in ({0})
if (ret == 0) ret = t1.Name.CompareTo(t2.Name); if (ret == 0) ret = t1.Name.CompareTo(t2.Name);
return ret; return ret;
}); });
foreach (var loc4 in loc1) {
var dicUniques = new Dictionary<string, List<DbColumnInfo>>();
dicUniques.Add(string.Join(",", loc4.Primarys.Select(a => a.Name)), loc4.Primarys);
foreach (var loc5 in loc4.Uniques) {
var dickey = string.Join(",", loc5.Select(a => a.Name));
if (dicUniques.ContainsKey(dickey)) continue;
dicUniques.Add(dickey, loc5);
}
loc4.Uniques = dicUniques.Values.ToList();
}
loc2.Clear(); loc2.Clear();
loc3.Clear(); loc3.Clear();

View File

@ -231,7 +231,8 @@ namespace test.Model {
var affrows = mysql.Update<{#UString(table.Name)}>().Where(a => {#parmsByWhereLambda}).ExecuteAffrows(); var affrows = mysql.Update<{#UString(table.Name)}>().Where(a => {#parmsByWhereLambda}).ExecuteAffrows();
if (affrows > 0) return; if (affrows > 0) return;
}{/if} }{/if}
{if pks.Count > 0}this.{#UString(idensCol.Name)} = {#GetCsType(idensCol).Replace("?", "") == "long" ? "" : ("(" + GetCsType(idensCol) + ")")}mysql.Insert<{#UString(table.Name)}>().AppendData(this).ExecuteIdentity();{else}mysql.Insert<{#UString(table.Name)}>().AppendData(this).ExecuteAffrows();{/if} {if idens > 0}this.{#UString(idensCol.Name)} = {#GetCsType(idensCol).Replace("?", "") == "long" ? "" : ("(" + GetCsType(idensCol) + ")")}mysql.Insert<{#UString(table.Name)}>().AppendData(this).ExecuteIdentity();{else}
mysql.Insert<{#UString(table.Name)}>().AppendData(this).ExecuteAffrows();{/if}
} }
{/if} {/if}
} }