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.

66 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 PostgreSQLCodeFirst : 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 result = new DbColumnInfo
  26. {
  27. DataType = this.Context.Ado.DbBind.GetDbTypeName(UtilMethods.GetUnderType(item.PropertyInfo).Name),
  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. if (result.DataType.Equals("varchar", StringComparison.CurrentCultureIgnoreCase) && result.Length == 0)
  39. {
  40. result.Length = 1;
  41. }
  42. return result;
  43. }
  44. protected override void ConvertColumns(List<DbColumnInfo> dbColumns)
  45. {
  46. foreach (var item in dbColumns)
  47. {
  48. if (item.DataType == "DateTime")
  49. {
  50. item.Length = 0;
  51. }
  52. }
  53. }
  54. protected override void ChangeKey(EntityInfo entityInfo, string tableName, EntityColumnInfo item)
  55. {
  56. this.Context.DbMaintenance.UpdateColumn(tableName, EntityColumnToDbColumn(entityInfo, tableName, item));
  57. if (!item.IsPrimarykey)
  58. this.Context.DbMaintenance.DropConstraint(tableName,null);
  59. if (item.IsPrimarykey)
  60. this.Context.DbMaintenance.AddPrimaryKey(tableName, item.DbColumnName);
  61. }
  62. }
  63. }