Entity Framework 6以Code First方式搭建Sqlite数据库环境
对于EF支持Sqlite数据库映射,网上似乎说得都不是很清楚,自己研究了会儿,现在给大家分享下~
所使用的库版本
EntityFramework.6.1.0
SQLite.1.0.92.0
以上两个库可以通过nuget下载,具体下载方式不在此说明.
引用结构
配置
App.config配置
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <entityFramework> <providers> <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" /> </providers> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> <parameters> <parameter value="v11.0" /> </parameters> </defaultConnectionFactory> </entityFramework> <connectionStrings> <add name="NorthwindContext" connectionString="Data Source=Northwind.sl3" providerName="System.Data.SQLite.EF6" /> </connectionStrings> <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" /> </DbProviderFactories> </system.data> </configuration>
这里provider配置只需要System.Data.SQLite.EF6就行.
代码实现
继承DbContext,并定义实体
public class NorthwindContext : DbContext { public DbSet<Employee> Employees { get; set; } } public class Employee { public int EmployeeID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } }
测试
class Program { static void Main(string[] args) { NorthwindContext context = new NorthwindContext(); var empList = context.Employees.OrderBy(c => c.FirstName).ToList(); Console.WriteLine(empList.Count); Console.ReadLine(); } }
可以正确执行Linq.
参考:
http://hintdesk.com/sqlite-with-entity-framework-code-first-and-migration/
http://www.nullskull.com/a/10476742/sqlite-in-wpf-with-entity-framework-6.aspx
希望以上信息对你有用~