关于EF6用于SQlite的总结
关于Sqlite采用EF6操作的问题折腾里一整天,现在总结一下。
1、首先使用Nuget安装sqlite。安装成功后如图所示:
2、改配置文件 安装后,你会发现在app.config中,添加关于sqlite的配置。
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <connectionStrings> <!--添加连接字符串,注意后面的路径用全路径--> <add name="SqliteTest" providerName="System.Data.SQLite.EF6" connectionString="Data Source=|DataDirectory|\education.db;Pooling=True;BinaryGuid=False" /> </connectionStrings> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> <parameters> <parameter value="mssqllocaldb" /> </parameters> </defaultConnectionFactory> <providers> <!--在EntityFramework节点的providers子节点添加配置--> <provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" /> <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" /> </providers> </entityFramework> <system.data> <DbProviderFactories> <remove invariant="System.Data.SQLite.EF6" /> <add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" /> <remove invariant="System.Data.SQLite" /> <!--在system.data节点的DbProviderFactories子节点配置如下--> <add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" /> </DbProviderFactories> </system.data> </configuration>
3、创建实体类
[Table("Persons")]//注意Table标签 public class Person { [Key] public Guid Id { set; get; } public string Name { set; get; } }
4、创建一个类继承自DbContext,以后通过它访问数据库
public class SQliteDbContext:DbContext { public SQliteDbContext() : base("SqliteTest") { } public DbSet<Person> Persons { set; get; } }
5、调用
static void Main(string[] args) { using (var context = new SQliteDbContext()) { //foreach (var item in context.Persons) //{ // Console.WriteLine(item.Id); //} var tt = context.Persons.Find(new Guid("00114a15-aceb-4b92-b9f6-cc5df509c4d5")); Console.WriteLine(tt.Id); //for (int i = 0; i < 10000; i++) //{ // context.Persons.Add(new Person { Id = Guid.NewGuid(), Name = "kkk" }); //} context.SaveChanges(); } Console.ReadKey(); }