SQLiteContext.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using SQLite.CodeFirst;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel.DataAnnotations;
  5. using System.ComponentModel.DataAnnotations.Schema;
  6. using System.Data.Entity;
  7. using System.Data.Entity.Migrations;
  8. using System.Data.Entity.ModelConfiguration.Conventions;
  9. using System.Data.SQLite.EF6.Migrations;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. namespace SqliteEFDemo
  14. {
  15. internal sealed class ContextMigrationConfiguration : DbMigrationsConfiguration<SQLiteContext>
  16. {
  17. public ContextMigrationConfiguration()
  18. {
  19. // 启用自动迁移
  20. AutomaticMigrationsEnabled = true;
  21. // 允许自动迁移导致的数据丢失
  22. AutomaticMigrationDataLossAllowed = true;
  23. SetSqlGenerator("System.Data.SQLite", new SQLiteMigrationSqlGenerator());// the Golden Key
  24. ContextKey = "SQLiteDemoContext";
  25. }
  26. protected override void Seed(SQLiteContext context)
  27. {
  28. // This method will be called after migrating to the latest version.
  29. // You can use the DbSet<T>.AddOrUpdate() helper extension method
  30. // to avoid creating duplicate seed data.
  31. }
  32. }
  33. public class SQLiteContext:DbContext
  34. {
  35. static SQLiteContext()
  36. {
  37. Database.SetInitializer(new MigrateDatabaseToLatestVersion<SQLiteContext, ContextMigrationConfiguration>(true));
  38. }
  39. public SQLiteContext()
  40. : base("SqliteConn")
  41. {
  42. }
  43. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  44. {
  45. //解决EF动态建库数据库表名变为复数问题
  46. // modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
  47. //如果不存在数据库,则创建
  48. //Database.SetInitializer(new SqliteCreateDatabaseIfNotExists<SQLiteContext>(modelBuilder));
  49. }
  50. // 数据库表文件
  51. public DbSet<Person> Persons { get; set; }
  52. }
  53. [Table("Person")]
  54. public class Person
  55. {
  56. [Key]
  57. public Int64 Id { get; set; } //注意要用Int64
  58. public string FirstName { get; set; }
  59. public string LastName { get; set; }
  60. public string enable { get; set; }
  61. public string enable2 { get; set; }
  62. public string enable3 { get; set; }
  63. public string enable4 { get; set; }
  64. }
  65. }