技术交流 > 心得分享 > .net使用EF操作SQLite (codefirst vs2015)

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

1.Nuget导包

  • SQLite.CodeFirst

  • System.Data.SQLite

导入以上两个包即可,其他依赖包会自动导入


2.配置config

连接字符串
<connectionStrings>

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


3.支撑程序

<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>


4.编写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; }
    }
}


5.编写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));
        }
    }
}   


6.测试程序

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();            

}


2022-01-26 16:59:13
评论
  • 评论加载中...

评论内容: