Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. #! "netcoreapp2.1"
  2. #r "nuget:Microsoft.Extensions.DependencyInjection,2.1.0"
  3. #r "nuget:Microsoft.Extensions.DependencyInjection.Abstractions,2.1.0"
  4. #r "nuget:Npgsql.EntityFrameworkCore.PostgreSQL,2.1.0"
  5.  
  6. using System.ComponentModel.DataAnnotations;
  7. using Microsoft.EntityFrameworkCore;
  8. using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
  9. using Microsoft.Extensions.DependencyInjection;
  10.  
  11. public class Student {
  12. [Key]
  13. public int Id { set; get; }
  14.  
  15. public bool Height { set; get; }
  16. public bool Fast { set; get; }
  17. }
  18.  
  19. public class MyContext : DbContext {
  20. public MyContext(DbContextOptions options) : base(options) { }
  21. public DbSet<Student> Students { set; get; }
  22.  
  23. protected override void OnModelCreating(ModelBuilder builder) {
  24. builder.Entity<Student>().Property(x => x.Height).HasConversion(new BoolToStringConverter("OFF", "ON"));
  25. builder.Entity<Student>().Property(x => x.Fast).HasConversion(new BoolToTwoValuesConverter<string>("OFF", "ON"));
  26. }
  27. }
  28.  
  29. var collection = new ServiceCollection();
  30. collection.AddDbContextPool<MyContext>(options => {
  31. options.UseNpgsql("Host=localhost;User Id=postgres;Password=1234;Database=BoolToString");
  32. });
  33.  
  34. var provider = collection.BuildServiceProvider();
  35.  
  36. using (var context = provider.GetService<MyContext>()) {
  37. context.Database.EnsureDeleted();
  38. context.Database.EnsureCreated();
  39. context.Students.Add(new Student { Height = true, Fast = true });
  40. context.Students.Add(new Student { Height = false, Fast = false });
  41. context.SaveChanges();
  42. }
  43.  
  44. using (var context = provider.GetService<MyContext>()) {
  45. var students = context.Students.ToList();
  46. foreach (var item in students) {
  47. Console.WriteLine("Height: {0}, Fast: {1}", item.Height, item.Fast);
  48. }
  49. }
  50.  
  51. // Unexpected results
  52.  
  53. /*
  54. Height: True, Fast: True
  55. Height: False, Fast: False
  56. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement