From df07b7bcc4b6cfb16ced1566c0e0b1dc3e320a4f Mon Sep 17 00:00:00 2001 From: 28810 <28810@YEXIANGQIN> Date: Wed, 19 Dec 2018 12:06:04 +0800 Subject: [PATCH] =?UTF-8?q?SqlServer=20CodeFirst=20=E9=80=82=E9=85=8D?= =?UTF-8?q?=E5=AE=8C=E6=88=90=EF=BC=88=E5=90=8C=E6=AD=A5=E7=BB=93=E6=9E=84?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Docs/codefirst.md | 16 +--- .../Generator/MySqlTemplateGeneratorTest.cs | 2 +- .../SqlServer/SqlServerCodeFirstTest.cs | 70 +++++++++++++++++ FreeSql.Tests/g.cs | 3 +- FreeSql/MySql/MySqlDbFirst.cs | 10 +++ FreeSql/PostgreSQL/PostgreSQLDbFirst.cs | 10 +++ FreeSql/SqlServer/SqlServerCodeFirst.cs | 77 +++++++++++-------- FreeSql/SqlServer/SqlServerDbFirst.cs | 10 +++ .../Models/for-table.cs.freesql | 3 +- 9 files changed, 153 insertions(+), 48 deletions(-) create mode 100644 FreeSql.Tests/SqlServer/SqlServerCodeFirstTest.cs diff --git a/Docs/codefirst.md b/Docs/codefirst.md index 0bafd459..46ef96a8 100644 --- a/Docs/codefirst.md +++ b/Docs/codefirst.md @@ -1,18 +1,10 @@ # CodeFirst -### 支持的类型 +| 数据库 | 支持的类型类型 | +| - | - | +| MySql | bool, sbyte, short, int, long, byte, ushort, uint, ulong, double, float, decimal, Guid, TimeSpan, DateTime
bool?, sbyte?, short?, int?, long?, byte?, ushort?, uint?, ulong?, double?, float?, decimal?, Guid?, TimeSpan?, DateTime?
byte[], string, Enum & FlagsEnum
MygisPoint, MygisLineString, MygisPolygon, MygisMultiPoint, MygisMultiLineString, MygisMultiPolygon | +| SqlServer | bool, sbyte, short, int, long, byte, ushort, uint, ulong, double, float, decimal, Guid, TimeSpan, DateTime, DateTimeOffset
bool?, sbyte?, short?, int?, long?, byte?, ushort?, uint?, ulong?, double?, float?, decimal?, Guid?, TimeSpan?, DateTime?, DateTimeOffset?
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 IFreeSql fsql = new FreeSql.FreeSqlBuilder() diff --git a/FreeSql.Tests/Generator/MySqlTemplateGeneratorTest.cs b/FreeSql.Tests/Generator/MySqlTemplateGeneratorTest.cs index ff0e085b..51d97a35 100644 --- a/FreeSql.Tests/Generator/MySqlTemplateGeneratorTest.cs +++ b/FreeSql.Tests/Generator/MySqlTemplateGeneratorTest.cs @@ -21,7 +21,7 @@ namespace FreeSql.Tests.Generator { [Fact] public void BuildRichEntityNavigationObject() { 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"); } } } diff --git a/FreeSql.Tests/SqlServer/SqlServerCodeFirstTest.cs b/FreeSql.Tests/SqlServer/SqlServerCodeFirstTest.cs new file mode 100644 index 00000000..96785091 --- /dev/null +++ b/FreeSql.Tests/SqlServer/SqlServerCodeFirstTest.cs @@ -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(); + + + } + + + [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 } + } +} diff --git a/FreeSql.Tests/g.cs b/FreeSql.Tests/g.cs index 1f7f39b0..9ca30775 100644 --- a/FreeSql.Tests/g.cs +++ b/FreeSql.Tests/g.cs @@ -6,7 +6,8 @@ using System.Text; public class g { 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(); public static IFreeSql sqlserver = new FreeSql.FreeSqlBuilder() diff --git a/FreeSql/MySql/MySqlDbFirst.cs b/FreeSql/MySql/MySqlDbFirst.cs index 942c52ba..af4e4db1 100644 --- a/FreeSql/MySql/MySqlDbFirst.cs +++ b/FreeSql/MySql/MySqlDbFirst.cs @@ -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); return ret; }); + foreach(var loc4 in loc1) { + var dicUniques = new Dictionary>(); + 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(); loc3.Clear(); diff --git a/FreeSql/PostgreSQL/PostgreSQLDbFirst.cs b/FreeSql/PostgreSQL/PostgreSQLDbFirst.cs index f232571d..bbff5851 100644 --- a/FreeSql/PostgreSQL/PostgreSQLDbFirst.cs +++ b/FreeSql/PostgreSQL/PostgreSQLDbFirst.cs @@ -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); return ret; }); + foreach (var loc4 in loc1) { + var dicUniques = new Dictionary>(); + 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(); loc3.Clear(); diff --git a/FreeSql/SqlServer/SqlServerCodeFirst.cs b/FreeSql/SqlServer/SqlServerCodeFirst.cs index 49fda5d8..8d648818 100644 --- a/FreeSql/SqlServer/SqlServerCodeFirst.cs +++ b/FreeSql/SqlServer/SqlServerCodeFirst.cs @@ -22,40 +22,51 @@ namespace FreeSql.SqlServer { public bool IsAutoSyncStructure { get; set; } = true; - static readonly Dictionary _dicCsToDb = new Dictionary() { - { "System.Boolean", (SqlDbType.Bit, "bit","bit NOT NULL", null, false) },{ "System.Nullable`1[System.Boolean]", (SqlDbType.Bit, "bit","bit", null, true) }, + static object _dicCsToDbLock = new object(); + static Dictionary _dicCsToDb = new Dictionary() { + { 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) }, - { "System.Int16", (SqlDbType.SmallInt, "smallint","smallint NOT NULL", false, false) },{ "System.Nullable`1[System.Int16]", (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) }, - { "System.Int64", (SqlDbType.BigInt, "bigint","bigint NOT NULL", false, false) },{ "System.Nullable`1[System.Int64]", (SqlDbType.BigInt, "bigint","bigint", false, true) }, + { typeof(sbyte).FullName, (SqlDbType.TinyInt, "tinyint", "tinyint NOT NULL", false, false) },{ typeof(sbyte?).FullName, (SqlDbType.TinyInt, "tinyint", "tinyint", false, true) }, + { typeof(short).FullName, (SqlDbType.SmallInt, "smallint","smallint NOT NULL", false, false) },{ typeof(short?).FullName, (SqlDbType.SmallInt, "smallint", "smallint", false, true) }, + { typeof(int).FullName, (SqlDbType.Int, "int", "int NOT NULL", false, false) },{ typeof(int?).FullName, (SqlDbType.Int, "int", "int", 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) }, - { "System.UInt16", (SqlDbType.SmallInt, "smallint","smallint NOT NULL", true, false) },{ "System.Nullable`1[System.UInt16]", (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) }, - { "System.UInt64", (SqlDbType.BigInt, "bigint", "bigint NOT NULL", true, false) },{ "System.Nullable`1[System.UInt64]", (SqlDbType.BigInt, "bigint", "bigint", true, true) }, + { typeof(byte).FullName, (SqlDbType.TinyInt, "tinyint","tinyint NOT NULL", true, false) },{ typeof(byte?).FullName, (SqlDbType.TinyInt, "tinyint","tinyint", true, true) }, + { typeof(ushort).FullName, (SqlDbType.SmallInt, "smallint","smallint NOT NULL", true, false) },{ typeof(ushort?).FullName, (SqlDbType.SmallInt, "smallint", "smallint", true, true) }, + { typeof(uint).FullName, (SqlDbType.Int, "int", "int NOT NULL", true, false) },{ typeof(uint?).FullName, (SqlDbType.Int, "int", "int", 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) }, - { "System.Single", (SqlDbType.Real, "float","float NOT NULL", false, false) },{ "System.Nullable`1[System.Single]", (SqlDbType.Real, "float","float", 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(double).FullName, (SqlDbType.Float, "float", "float NOT NULL", false, false) },{ typeof(double?).FullName, (SqlDbType.Float, "float", "float", false, true) }, + { typeof(float).FullName, (SqlDbType.Real, "real","real NOT NULL", false, false) },{ typeof(float?).FullName, (SqlDbType.Real, "real","real", 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) }, - { "System.DateTime", (SqlDbType.DateTime, "datetime", "datetime NOT NULL", false, false) },{ "System.Nullable`1[System.DateTime]", (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(TimeSpan).FullName, (SqlDbType.Time, "time","time NOT NULL", false, false) },{ typeof(TimeSpan?).FullName, (SqlDbType.Time, "time", "time",false, true) }, + { typeof(DateTime).FullName, (SqlDbType.DateTime, "datetime", "datetime NOT NULL", false, false) },{ typeof(DateTime?).FullName, (SqlDbType.DateTime, "datetime", "datetime", 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) }, - { "System.String", (SqlDbType.NVarChar, "nvarchar", "nvarchar(255)", false, null) }, + { typeof(byte[]).FullName, (SqlDbType.VarBinary, "varbinary", "varbinary(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) { + 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; if (enumType == null && type.FullName.StartsWith("System.Nullable`1[") && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First(); 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() => this.GetComparisonDDLStatements(typeof(TEntity)); @@ -70,11 +81,11 @@ namespace FreeSql.SqlServer { var isRenameTable = false; var tbname = tb.DbName.Split(new[] { '.' }, 2); 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; } else { @@ -87,7 +98,7 @@ namespace FreeSql.SqlServer { if (tbcol.Attribute.IsPrimary) sb.Append(" primary key"); 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; } } @@ -96,7 +107,7 @@ namespace FreeSql.SqlServer { foreach (var tbcol in tb.Columns) addcols.Add(tbcol.Value.Attribute.Name, tbcol.Value); var surplus = new Dictionary(StringComparer.CurrentCultureIgnoreCase); var dbcols = new List(); - var sql = @"select + var sql = string.Format(@"select a.name 'Column' ,b.name + case 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 + ')' when b.name in ('Numeric', 'Decimal') then '(' + cast(a.precision as varchar) + ',' + cast(a.scale as varchar) + ')' else '' end as 'SqlType' -,a.is_nullable 'IsNullable' -,a.is_identity 'IsIdentity' +,case when a.is_nullable = 1 then '1' else '0' end 'IsNullable' +,case when a.is_identity = 1 then '1' else '0' end 'IsIdentity' from sys.columns a 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.tables d on d.object_id = a.object_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); foreach (var row in ds) { 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) { 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)"); - sb.Append(" GO \r\n"); + sb.Append(" \r\nGO \r\n"); } addcols.Remove(column); } else @@ -134,15 +145,15 @@ where a.object_id in (object_id(N'[{0}].[{1}]'))".FormatMySql(isRenameTable ? tb } foreach (var addcol in addcols.Values) { 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()); 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 { //添加列 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)"); - sb.Append(" GO \r\n"); + sb.Append(" \r\nGO \r\n"); } } } diff --git a/FreeSql/SqlServer/SqlServerDbFirst.cs b/FreeSql/SqlServer/SqlServerDbFirst.cs index e57c2037..361d0761 100644 --- a/FreeSql/SqlServer/SqlServerDbFirst.cs +++ b/FreeSql/SqlServer/SqlServerDbFirst.cs @@ -374,6 +374,16 @@ where b.object_id in ({0}) if (ret == 0) ret = t1.Name.CompareTo(t2.Name); return ret; }); + foreach (var loc4 in loc1) { + var dicUniques = new Dictionary>(); + 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(); loc3.Clear(); diff --git a/Templates/MySql/rich-entity-navigation-object/Models/for-table.cs.freesql b/Templates/MySql/rich-entity-navigation-object/Models/for-table.cs.freesql index e9be6c3a..a33178b3 100644 --- a/Templates/MySql/rich-entity-navigation-object/Models/for-table.cs.freesql +++ b/Templates/MySql/rich-entity-navigation-object/Models/for-table.cs.freesql @@ -231,7 +231,8 @@ namespace test.Model { var affrows = mysql.Update<{#UString(table.Name)}>().Where(a => {#parmsByWhereLambda}).ExecuteAffrows(); if (affrows > 0) return; }{/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} }