.net使用EF操作SQLite (codefirst vs)

时间:2024-03-13 12:54:47

.net使用EF操作SQLite (codefirst vs2015)

配置config


连接字符串
  <connectionStrings>
    <add name="sqliteconn" connectionString="data source=sqLiteTestDB.db" providerName="System.Data.SQLite.EF6"/>
  </connectionStrings>

支撑程序


   <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
      <provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />

    </providers>

编写model类


    using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace safetodelete_efSqLite_ConsoleApplication1
{
    [Table("employee")]
    class Employee
    {
        [Key]
        public String employeeId { get; set; }
        public String name { get; set; }
    }
}

编写context类


    using System.Data.Entity;
using System.Data.Common;
using System.Data.SQLite.EF6;
using SQLite.CodeFirst;

namespace safetodelete_efSqLite_ConsoleApplication1
{
    class EmployeeContext : DbContext
    {
        public EmployeeContext() : base("sqliteconn") { }

        public EmployeeContext(DbConnection sqliteCon) : base("sqliteconn")
        {
            this.sqliteCon = sqliteCon;
        }
        public DbSet<Employee> employees { get; set; }
        static string dbPath = @"data source=sqLiteTestDB.db";
        private DbConnection sqliteCon;
        public static EmployeeContext Instance
        {
            get
            {
                DbConnection sqliteCon = SQLiteProviderFactory.Instance.CreateConnection();
                sqliteCon.ConnectionString = dbPath;
                return new EmployeeContext(sqliteCon);
            }
        }      
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //如果不存在数据库,则创建
            Database.SetInitializer(new SqliteCreateDatabaseIfNotExists<EmployeeContext>(modelBuilder));
        }
    }
}    

测试程序


           static void Main(string[] args)
        {

            Employee e1 = new Employee();
            e1.employeeId = Guid.NewGuid().ToString();
            e1.name = "xiaoming";

            EmployeeContext ec = new EmployeeContext();
            ec.employees.Add(e1);
            ec.SaveChanges();     

            Console.WriteLine("hello world");
            Console.ReadKey();            

        }