DataSource.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 SqlDbContext CreateDbContextForWriting() => CreateDbContext();
  25. public static SqlDbContext CreateDbContext()
  26. {
  27. var guid = Guid.NewGuid().ToString();
  28. var filePath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, $"{guid}.sqlite.db");
  29. if (File.Exists(filePath)) File.Delete(filePath);
  30. File.WriteAllBytes(filePath, new byte[0]);
  31. var connectionString = $"data source={filePath}";
  32. var dbContext = new SqlDbContext();
  33. dbContext.UseSqlite(connectionString);
  34. dbContext.BeginTransaction();
  35. var dbSet = dbContext.DbSet<User>();
  36. dbSet.Create();
  37. var users = new List<User> {
  38. new User { id=1, name="u146", fatherId=4, motherId=6 },
  39. new User { id=2, name="u246", fatherId=4, motherId=6 },
  40. new User { id=3, name="u356", fatherId=5, motherId=6 },
  41. new User { id=4, name="u400" },
  42. new User { id=5, name="u500" },
  43. new User { id=6, name="u600" },
  44. };
  45. users.ForEach(user => { user.birth = DateTime.Parse("2021-01-01 00:00:00").AddHours(user.id); });
  46. dbContext.AddRange(users);
  47. return dbContext;
  48. }
  49. }
  50. }