DataSource.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using Vit.Extensions;
  2. using Vitorm.Sql;
  3. namespace Vitorm.MsTest
  4. {
  5. [System.ComponentModel.DataAnnotations.Schema.Table("User")]
  6. public class User
  7. {
  8. [System.ComponentModel.DataAnnotations.Key]
  9. public int id { get; set; }
  10. public string name { get; set; }
  11. public DateTime? birth { get; set; }
  12. public int? fatherId { get; set; }
  13. public int? motherId { get; set; }
  14. [System.ComponentModel.DataAnnotations.Schema.NotMapped]
  15. public string test { get; set; }
  16. public static User NewUser(int id, bool forAdd = false) => new User { id = id, name = "testUser" + id };
  17. public static List<User> NewUsers(int startId, int count = 1, bool forAdd = false)
  18. {
  19. return Enumerable.Range(startId, count).Select(id => NewUser(id, forAdd)).ToList();
  20. }
  21. }
  22. public class DataSource
  23. {
  24. public static void WaitForUpdate() { }
  25. public static SqlDbContext CreateDbContextForWriting() => CreateDbContext();
  26. public static SqlDbContext CreateDbContext()
  27. {
  28. var guid = Guid.NewGuid().ToString();
  29. var filePath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, $"{guid}.sqlite.db");
  30. if (File.Exists(filePath)) File.Delete(filePath);
  31. File.WriteAllBytes(filePath, new byte[0]);
  32. var connectionString = $"data source={filePath}";
  33. var dbContext = new SqlDbContext();
  34. dbContext.UseSqlite(connectionString);
  35. dbContext.BeginTransaction();
  36. var dbSet = dbContext.DbSet<User>();
  37. dbSet.Create();
  38. var users = new List<User> {
  39. new User { id=1, name="u146", fatherId=4, motherId=6 },
  40. new User { id=2, name="u246", fatherId=4, motherId=6 },
  41. new User { id=3, name="u356", fatherId=5, motherId=6 },
  42. new User { id=4, name="u400" },
  43. new User { id=5, name="u500" },
  44. new User { id=6, name="u600" },
  45. };
  46. users.ForEach(user => { user.birth = DateTime.Parse("2021-01-01 00:00:00").AddHours(user.id); });
  47. dbContext.AddRange(users);
  48. return dbContext;
  49. }
  50. }
  51. }