EF6+CodeFirst + SQLite 数据库

109 0
  • 引用包以及其依赖

    SQLite.EF6.Migrations
    SQLite.CodeFirst
  • 定义一个类

public class SysConfiguration : DbMigrationsConfiguration
{
    public SysConfiguration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = true;
        SetSqlGenerator("System.Data.SQLite", new SQLiteMigrationSqlGenerator());
    }

    protected override void Seed(DBContext context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet.AddOrUpdate() helper extension method 
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //

    }
}
  • 在 DBContext 中的构造函数DBContext()加上
  Database.SetInitializer(new MigrateDatabaseToLatestVersion());
  • 报错ProviderIncompatibleException: CreateDatabase is not supported by the provider.

    检查数据库路径,文件夹需要手动创建。

  • 完整的Context数据库上下文,以及配置类

using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.SQLite.EF6.Migrations;
using XuJoe.Model;

namespace XuJoe.Context
{
    #region 1.创建数据库上下文   类
    public class SysContext : DbContext
    {
        // You can add custom code to this file. Changes will not be overwritten.
        // 
        // If you want Entity Framework to drop and regenerate your database
        // automatically whenever you change your model schema, please use data migrations.
        // For more information refer to the documentation:
        // http://msdn.microsoft.com/en-us/data/jj591621.aspx

        public SysContext() : base("name=SysContext")
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<SysContext, SysConfiguration>());
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {//Fluent API(重写 OnModelCreating 方法) 的方式来配置模型

            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            modelBuilder.Configurations.AddFromAssembly(typeof(SysContext).Assembly);
            // modelBuilder.Entity<LineChartTag>().HasIndex(u => u.Tag).IsUnique();//Tag唯一
        }
        //添加数据库需要创建表的模型
        public System.Data.Entity.DbSet<ControlInfo> ControlInfoList { get; set; }
    }

    #endregion

    #region 2. 在创建与上下文匹配的 配置类继承DbMigrationsConfiguration<T>
    public class SysConfiguration : DbMigrationsConfiguration<SysContext>
    {
        public SysConfiguration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
            SetSqlGenerator("System.Data.SQLite", new SQLiteMigrationSqlGenerator());
        }

        protected override void Seed(SysContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //

        }
    }
    #endregion

    #region 3.App.config配置文件添加name=SysContext的数据库连接字符串

    //     在<configuration></configuration>节点中添加connectionStrings
    //    <connectionStrings>
    //        <add name = "SysContext" connectionString="Data Source=.\db\Sys.db;Pooling=true;FailIfMissing=false" providerName="System.Data.SQLite" />
    //    </connectionStrings>
    #endregion

    #region 4.在App.config配置文件中的providers添加一个provider,检查DbProviderFactories

    // configuration->entityFramework->providers 添加下一行
    // <provider invariantName = "System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />

    //否则会报一下错
    // 没有修改App.config配置文件其他
    // System.InvalidOperationException:“No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SQLite'. Make sure the provider is registered in the 'entityFramework' section of the application config file. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.”

    //检查DbProviderFactories里是否有
    //<remove invariant = "System.Data.SQLite" />
    //< add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />

    #endregion

    #region 5.其他一些常见的报错
    // 连接字符串的数据源指向文件位置没有对应的文件夹   例如Data Source=.\db\Sys.db;根目录上没有db文件夹 会报错 手动创建db文件夹即可
    //    System.Data.DataException:“An exception occurred while initializing the database.See the InnerException for details.”
    //      内部异常:ProviderIncompatibleException: CreateDatabase is not supported by the provider.

    //报错 模型里没有字段报错:
    //System.Data.Entity.ModelConfiguration.ModelValidationException:“One or more validation errors were detected during model generation:
    #endregion
}

发表评论