diff --git a/SqlServerTest/Demos/5_CodeFirst.cs b/SqlServerTest/Demos/5_CodeFirst.cs index e5f76fb0f..eecdbee2e 100644 --- a/SqlServerTest/Demos/5_CodeFirst.cs +++ b/SqlServerTest/Demos/5_CodeFirst.cs @@ -11,8 +11,8 @@ namespace OrmTest.Demo [SugarColumn(IsNullable =false ,IsPrimaryKey =true,IsIdentity =true)] public int Id { get; set; } - [SugarColumn(Length = 21)] - public string Name { get; set; } + [SugarColumn(Length = 21,OldColumnName = "Name2")] + public string Name{ get; set; } [SugarColumn(IsNullable = true)] public bool IsOk { get; set; } public Guid Guid { get; set; } diff --git a/SqlSugar/Abstract/CodeFirstProvider/CodeFirstProvider.cs b/SqlSugar/Abstract/CodeFirstProvider/CodeFirstProvider.cs index 258c0ed83..af2bfee28 100644 --- a/SqlSugar/Abstract/CodeFirstProvider/CodeFirstProvider.cs +++ b/SqlSugar/Abstract/CodeFirstProvider/CodeFirstProvider.cs @@ -70,6 +70,7 @@ namespace SqlSugar private void NoExistLogic(EntityInfo entityInfo) { var tableName = GetTableName(entityInfo); + Check.Exception(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1, "Use Code First ,The primary key must not exceed 1"); List columns = new List(); if (entityInfo.Columns.IsValuable()) { @@ -80,6 +81,11 @@ namespace SqlSugar } } this.Context.DbMaintenance.CreateTable(tableName, columns); + var pkColumns= entityInfo.Columns.Where(it => it.IsPrimarykey).ToList(); + foreach (var item in pkColumns) + { + this.Context.DbMaintenance.AddPrimaryKey(tableName, item.DbColumnName); + } } private void ExistLogic(EntityInfo entityInfo) { @@ -133,6 +139,7 @@ namespace SqlSugar foreach (var item in entityColumns) { var dbColumn = dbColumns.FirstOrDefault(dc => dc.DbColumnName.Equals(item.DbColumnName, StringComparison.CurrentCultureIgnoreCase)); + if (dbColumn == null) continue; var pkDiff = item.IsPrimarykey != dbColumn.IsPrimarykey; var idEntityDiff = item.IsIdentity != dbColumn.IsIdentity; if (dbColumn != null && pkDiff && !idEntityDiff) diff --git a/SqlSugar/Abstract/DbMaintenanceProvider/Methods.cs b/SqlSugar/Abstract/DbMaintenanceProvider/Methods.cs index 7f6d43d9a..bc1d2142b 100644 --- a/SqlSugar/Abstract/DbMaintenanceProvider/Methods.cs +++ b/SqlSugar/Abstract/DbMaintenanceProvider/Methods.cs @@ -180,7 +180,7 @@ namespace SqlSugar string dataType = item.DataType; string dataSize = item.Length > 0 ? string.Format("({0})", item.Length) : null; string nullType = item.IsNullable ? this.CreateTableNull : CreateTableNotNull; - string primaryKey = item.IsPrimarykey ? this.CreateTablePirmaryKey : null; + string primaryKey = null; string identity = item.IsIdentity ? this.CreateTableIdentity : null; string addItem = string.Format(this.CreateTableColumn, columnName, dataType, dataSize, nullType, primaryKey, identity); columnArray.Add(addItem);