首页 > 代码库 > EF6 在 SQLite中使用备忘

EF6 在 SQLite中使用备忘

== 菜鸟级选手试验在EF6中使用Sqlite,零EF基础,少量Sqlite基础。经过断断续续的很长时间 - _ -!

>>连接

1. 安装

   使用目前最新版本EF6.1,Sqlite1.0.93.0。直接NuGet安装:

   

2. 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?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" />
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <connectionStrings>
    <add name="SqlliteEF6" connectionString="Data Source=Data\EF6.db" providerName="System.Data.SQLite" />  </connectionStrings>
  <entityFramework>
    <providers>
      <provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
      <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=http://www.mamicode.com/"v11.0" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
  <system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SQLite" />
      <add name="SQLite Data Provider" invariant="System.Data.SQLite" description="Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
      <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>

 3. 设置数据库

    EF中数据库操作继承DBContext。需要指定数据连接,名称和config配置一致,否则默认使用Sqlserver。

    SQLite可以重载创建。

 

1
2
3
4
5
6
7
8
9
10
11
public class EF6Context : DbContext
    {
        public EF6Context(string databaseName = "SqlliteEF6")
            base(databaseName)
        {
        }
 
        public DbSet<User> Users { setget; }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {}
     }
 

 

  

>>注意事项

1. Sqlite中不能自动创建数据库和新建表,需要额外的操作

>> 数据类型插入获取

1. 自增ID

   Sqlite中需要设置AUTOINCREMENT,如下:

1
Id INTEGER PRIMARY KEY AUTOINCREMENT,

需要引用System.ComponentModel.DataAnnotations,System.ComponentModel.DataAnnotations.Schema,类中写明

1
2
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Int64 Id { get; set; }

2. 限定Table

  默认数据库获取为DBContext中定义的名称,限定对应的Table,需要在类上指明,如下:

1
2
3
[Table("User")]
public class User
{...

3. 枚举型

   目前直接能使用,注意需要在定义表时限定不能为NULL,否则为NULL时获取会报错。定义时如下定义:

1
public enum TestENUM : long { A, B, C };

 

4. 其它

   目前SQlite中支持浮点数、时间、二进制数据、字符串等。创建表示例:

1
2
3
4
5
6
7
8
9
NorthwindContext context = new NorthwindContext();
           string sql = @" CREATE TABLE User (
   Id INTEGER PRIMARY KEY AUTOINCREMENT,
   Name varchar (20),
   Time timestamp,
   Data blob,
   Val REAL,
   TestE INTEGER);";
           context.Database.ExecuteSqlCommand(sql, new object[1]);

   定义类示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[Table("User")]
public class User
{
    public enum TestENUM : long { A, B, C };
 
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Int64 Id { get; set; }
    [StringLength(30)]
    public string Name { get; set; }
 
    public byte[] Data { get; set; }
 
    public double Val { get; set; }
 
    public DateTime Time { get; set; }
    public TestENUM TestE { get; set; } 
}

  

1
2
3
4
5
6
7
8
9
10
11
public class EF6Context : DbContext
    {
        public EF6Context(string databaseName = "SqlliteEF6")
            base(databaseName)
        {
        }
 
        public DbSet<User> Users { setget; }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {}
     }
 

 

     调用示例:

 

1
2
3
NorthwindContext context = new NorthwindContext();
context.Users.Add(new User() { Data = http://www.mamicode.com/new byte[] { 1, 2, 3, 4 }, Name = "aa22", Time = DateTime.Now, Val = 2.2, TestE  = User.TestENUM.B });
context.SaveChanges();

 

1
2
3
NorthwindContext context = new NorthwindContext();
context.Users.OrderBy(c => c.Name).Load();
this.dataGrid.ItemsSource = context.Users.Local;

    以上代码测试正常。源码下载

 

 

 



来自为知笔记(Wiz)