You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
2.6 KiB

2 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace SqlSugar
  5. {
  6. public class MySqlCodeFirst : CodeFirstProvider
  7. {
  8. public override void NoExistLogic(EntityInfo entityInfo)
  9. {
  10. var tableName = GetTableName(entityInfo);
  11. Check.Exception(entityInfo.Columns.Count(it => it.IsPrimarykey)> 1, "Use Code First ,The primary key must not exceed 1");
  12. var columns = new List<DbColumnInfo>();
  13. if (entityInfo.Columns.HasValue())
  14. {
  15. foreach (var item in entityInfo.Columns)
  16. {
  17. var dbColumnInfo = this.EntityColumnToDbColumn(entityInfo, tableName, item);
  18. columns.Add(dbColumnInfo);
  19. }
  20. }
  21. this.Context.DbMaintenance.CreateTable(tableName, columns);
  22. }
  23. protected override DbColumnInfo EntityColumnToDbColumn(EntityInfo entityInfo, string tableName, EntityColumnInfo item)
  24. {
  25. var propertyType = UtilMethods.GetUnderType(item.PropertyInfo);
  26. var result = new DbColumnInfo
  27. {
  28. TableId = entityInfo.Columns.IndexOf(item),
  29. DbColumnName = item.DbColumnName.HasValue() ? item.DbColumnName : item.PropertyName,
  30. IsPrimarykey = item.IsPrimarykey,
  31. IsIdentity = item.IsIdentity,
  32. TableName = tableName,
  33. IsNullable = item.IsNullable,
  34. DefaultValue = item.DefaultValue,
  35. ColumnDescription = item.ColumnDescription,
  36. Length = item.Length
  37. };
  38. GetDbType(item, propertyType, result);
  39. if (result.DataType.Equals("varchar", StringComparison.CurrentCultureIgnoreCase) && result.Length == 0)
  40. {
  41. result.Length = 1;
  42. }
  43. return result;
  44. }
  45. protected override void ConvertColumns(List<DbColumnInfo> dbColumns)
  46. {
  47. foreach (var item in dbColumns)
  48. {
  49. if (item.DataType == "DateTime")
  50. {
  51. item.Length = 0;
  52. }
  53. }
  54. }
  55. protected override void ChangeKey(EntityInfo entityInfo, string tableName, EntityColumnInfo item)
  56. {
  57. this.Context.DbMaintenance.UpdateColumn(tableName, EntityColumnToDbColumn(entityInfo, tableName, item));
  58. if (!item.IsPrimarykey)
  59. this.Context.DbMaintenance.DropConstraint(tableName,null);
  60. if (item.IsPrimarykey)
  61. this.Context.DbMaintenance.AddPrimaryKey(tableName, item.DbColumnName);
  62. }
  63. }
  64. }