DataSource.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using Vitorm.Sql;
  2. using Vit.Extensions;
  3. using Vit.Core.Util.ConfigurationManager;
  4. using System.ComponentModel.DataAnnotations.Schema;
  5. namespace Vitorm.MsTest
  6. {
  7. [System.ComponentModel.DataAnnotations.Schema.Table("User", Schema = "dbo")]
  8. public class User
  9. {
  10. [System.ComponentModel.DataAnnotations.Key]
  11. [System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  12. [System.ComponentModel.DataAnnotations.Schema.Column("id", TypeName = "int")]
  13. public int id { get; set; }
  14. [System.ComponentModel.DataAnnotations.Schema.Column("name", TypeName = "varchar(1000)")]
  15. [System.ComponentModel.DataAnnotations.Required]
  16. public string name { get; set; }
  17. public DateTime? birth { get; set; }
  18. public int? fatherId { get; set; }
  19. public int? motherId { get; set; }
  20. [System.ComponentModel.DataAnnotations.Schema.NotMapped]
  21. public string test{ get; set; }
  22. public static User NewUser(int id, bool forAdd = false) => new User { id = forAdd ? 0 : id, name = "testUser" + id };
  23. public static List<User> NewUsers(int startId, int count = 1, bool forAdd = false)
  24. {
  25. return Enumerable.Range(startId, count).Select(id => NewUser(id, forAdd)).ToList();
  26. }
  27. }
  28. public class DataSource
  29. {
  30. public static void WaitForUpdate() { }
  31. static string connectionString = Appsettings.json.GetStringByPath("Vitorm.SqlServer.connectionString");
  32. public static SqlDbContext CreateDbContextForWriting() => CreateDbContext();
  33. public static SqlDbContext CreateDbContext()
  34. {
  35. var dbContext = new SqlDbContext();
  36. dbContext.UseSqlServer(connectionString);
  37. dbContext.BeginTransaction();
  38. dbContext.Execute(sql: "IF OBJECT_ID(N'User', N'U') IS NOT NULL \r\nDROP TABLE [User];");
  39. dbContext.Create<User>();
  40. var users = new List<User> {
  41. new User { name="u146", fatherId=4, motherId=6 },
  42. new User { name="u246", fatherId=4, motherId=6 },
  43. new User { name="u356", fatherId=5, motherId=6 },
  44. new User { name="u400" },
  45. new User { name="u500" },
  46. new User { name="u600" },
  47. };
  48. dbContext.AddRange(users);
  49. users.ForEach(user => { user.birth = DateTime.Parse("2021-01-01 00:00:00").AddHours(user.id); });
  50. dbContext.UpdateRange(users);
  51. return dbContext;
  52. }
  53. }
  54. }