记录一下通过 EntityFramework6 来操作sqlite过程

环境:

  • visual studio 2017
  • .net 4.5
  • Console Application(项目类型)
  • sqlite3
  • navicat for sqlite

设计数据库

我使用了 navicat for sqlite 这个图形界面工具来快速生成数据库的;

非常简单,打开 navicat ,按照下图操作即可



新建表:

Entry表(Id为主键,勾选自增),Type_Id为外键.



EntryType表(Id为主键,勾选自增)

完事之后点击左上角的保存!

在visual studio中建立控制台项目,安装必要的nuget包

打开nuget包管理工具,

在Browse选项卡中搜索 System.Data.SQLite

安装相应的nuget包,如图所示



之后在nuget包管理工具中查看已安装的nuget包

如下图:



然后在解决方案浏览器下可以看到App.config文件,



进去修改一下内容,在 provider 节点下加入下面的内容:

<provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />

建立 Entity 实体类

Entry 类 :

Entry
namespace MagicMemory.Core.Entities
{
public class Entry
{
public int Id { get; set; }
public string Key { get; set; }
public string Content { get; set; }
public int? EntryTypeId { get; set; }
public virtual EntryType Type { get; set; }
}
}

这里值得注意的是,Entry实体中有一个外键属性:

public virtual EntryType Type { get; set; }

一定要用virtual来修饰,这里不清楚为啥,我也是偶然看见的,不用virual就没用,可能因为是Dbfirst的原因,之前在.net core结合efcore使用的时候并不需要加virtual也行.这里的外键属性,Ef 会自动从数据库里相应的表中给我们映射过来.但是这个外键所在表也必须在 DbContext中作为DbSet<>的泛型参数存在才可以.

EntryType 类:

EntryType
using System;

namespace MagicMemory.Core.Entities

{

public class EntryType

{

public int Id { get; set; }

public string Name { get; set; }

}

}

实体类就这两个,差不多可以说明问题了,建立实体类的时候,实体类的属性名一定要和表的字段名相匹配(必须一样才行),名称不一样的话,则需要在属性的上方加一个注解属性 Column("Name").也可以使用fluentApi来进行配置,我跟喜欢这种方式,在DbContext中重写OnModelCreating()方法,对 column 进行配置.

当实体类型的属性名需要和不同名称的的表中的列进行映射时,可以使用下面的方法.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Property(b => b.BlogId)
.HasColumnName("blog_id");
}

继承DbContext,建立数据库上下文 xxxContext 类

EntryContext
using System.Data.Entity;
using System.Data.SQLite;
using MagicMemory.Core.Entities;
using SQLite.CodeFirst; namespace MagicMemory.DbStudy

{

public class EntryContext:DbContext

{

public EntryContext():base(new SQLiteConnection("Data Source=MagicMemory.Db"),true)

{

}
    protected override void OnModelCreating(DbModelBuilder builder)
{
builder.Entity&lt;Entry&gt;().ToTable(&quot;Entry&quot;);
builder.Entity&lt;Entry&gt;()
.Property(e =&gt; e.EntryTypeId)
.HasColumnName(&quot;EntryTypeId&quot;); builder.Entity&lt;EntryType&gt;().ToTable(&quot;EntryType&quot;); builder.Entity&lt;EntryTag&gt;().ToTable(&quot;EntryTagTable&quot;);
builder.Entity&lt;EntryTag&gt;()
.Property(t =&gt; t.Name)
.HasColumnName(&quot;TagName&quot;); base.OnModelCreating(builder); Database.SetInitializer(new SqliteDropCreateDatabaseWhenModelChanges&lt;EntryContext&gt;(builder));
} public DbSet&lt;Entry&gt; Entry { get; set; }
public DbSet&lt;EntryType&gt; EntryType { get; set; }
public DbSet&lt;EntryTag&gt; EntryTag { get; set; }
}

}

这里比较重要的是重写了 OnModelCreating() 方法,这个方法里面通过 fluent api的方式定义了实体类的属性和具体的数据库的字段的映射的关系;同时,在默认的构造函数里面,调用基类的构造函数,因为使用sqlite这个数据库,所以将继承了DbConnection的实例: new SQLiteConnection("[连接字符串]") 传递给基类的构造函数,用来连接数据库.

  </div>

通过EntityFramework操作sqlite(DbFirst)的更多相关文章

  1. 使用entityframework操作sqlite数据库

    首先要安装好,所需要的类库,通过NuGet来处理 http://stackoverflow.com/questions/28507904/vs-2015-sqlite-data-provider 安装 ...

  2. EF操作sqlite数据库时的项目兼容性问题

    问题:vs2015打不开vs2010建的操作sqlite的实体数据模型edmx文件 原因: 当前电脑必须先安装:驱动库及sqlite的vs拓展 正常情况下安装驱动和拓展后,vs2015就应该可以正常打 ...

  3. 【UWP】利用EF Core操作SQLite

    在以往开发中,一定要在vs中安装SQLite for Universal App Platform以及一款wrapper,如SQLitePCL.现在有了EntitfyFramewrok Core,我们 ...

  4. Java操作Sqlite数据库-jdbc连接

    Java操作Sqlite数据库步骤: 1. 导入Sqlite jdbc 本文使用sqlite-jdbc-3.7.2.jar,下载地址 http://pan.baidu.com/s/1kVHAGdD 2 ...

  5. C#操作SQLite数据库

    SQLite介绍 SQLite is a software library that implements a self-contained, serverless, zero-configurati ...

  6. 无废话Android之android下junit测试框架配置、保存文件到手机内存、android下文件访问的权限、保存文件到SD卡、获取SD卡大小、使用SharedPreferences进行数据存储、使用Pull解析器操作XML文件、android下操作sqlite数据库和事务(2)

    1.android下junit测试框架配置 单元测试需要在手机中进行安装测试 (1).在清单文件中manifest节点下配置如下节点 <instrumentation android:name= ...

  7. 操作SQLite的dbhelper

    操作SQLite的dbhelper public class DbHelper { string connStr = @"Data Source=" + System.Enviro ...

  8. python操作sqlite数据库

    root@cacti:~/box# cat convert.py #!/usr/bin/env python import sqlite3,time,rrdtool,os def boxstatus( ...

  9. .NET中操作SQLite

    C#操作SQLite Database C#下SQLite操作驱动dll下载:System.Data.SQLite C#使用SQLite步骤: (1)新建一个project (2)添加SQLite操作 ...

随机推荐

  1. 隐马尔科夫_HMM

    有向图 抽象:λ代表输入:输入一个句子,λi表示句子中的每个字 O代表输出:[B词首/M词中/E词尾/S单独成词] max=maxP(O1 O2 On/ λ1 λ2 λn) 假设: (1)当前观察值只 ...

  2. Photoshop零基础教程集锦,助你快速进阶为大佬,轻松、任性!!!

    现今,对于Web或App UI设计师而言,除了不断学习专业知识,提升设计技能.掌握一款得心应手的设计工具(例如设计师们常用的图像处理工具PhotoShop,矢量图绘制工具AI, 图形视频处理工具AE, ...

  3. Sliding Window Median LT480

    Median is the middle value in an ordered integer list. If the size of the list is even, there is no ...

  4. python数据结构详解

    Python中常见的数据结构可以统称为容器(container).序列(如列表和元组).映射(如字典)以及集合(set)是三类主要的容器. 一.序列(列表.元组和字符串) 序列中的每个元素都有自己的编 ...

  5. 爬虫模块之解决IO

    一 asyncio模块 asyncio模块:主要是帮我们检测IO(只能是网路IO). @asyncio.coroutine:装饰器 tasks:任务列表 get_event_loop:起任务 run_ ...

  6. 2019.01.21 bzoj1758: [Wc2010]重建计划(01分数规划+长链剖分+线段树)

    传送门 长链剖分好题. 题意简述:给一棵树,问边数在[L,R][L,R][L,R]之间的路径权值和与边数之比的最大值. 思路: 用脚指头想都知道要01分数规划. 考虑怎么checkcheckcheck ...

  7. The XOR Largest Pair(Tire字典树应用)

    题目链接:传送门 思路:建立一个32位的字典树,对每一个要插入的数字查找它异或的最大值(就是尽量全部二进制的值都相反), 然后获得两个数异或的最大值. #include<iostream> ...

  8. 使用express框架和mongoose在MongoDB更新数据

    update方法  modelName.update({需要替换的内容},{“$set”:{新的内容}},function(err,doc){}); User.update({userName:&qu ...

  9. (7)Why 30 is not the new 20

    https://www.ted.com/talks/meg_jay_why_30_is_not_the_new_20/transcript 00:12When I was in my 20s, I s ...

  10. GDI基础(2):绘制文本

    1.TextOut()和DrawText()函数 CDC::TextOut()在窗口的指定位置处输出文本,函数声明: virtual BOOL TextOut(int x, int y, LPCTST ...