• EntityFramework SQLite


    安装完sqlite的nuget包后,还要设置App.config文件才能正常使用

    1.  在<providers>节点添加一条提供器配置     

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

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

    这项配置看起来好像没有用到,但是不添加的话又会发生错误.


    2.  添加一个连接字符串节点<connectionStrings>用于添加数据库的连接字符串

    如添加一条连接字符串<add name="TestDb" connectionString="Data Source=TestDb.db" providerName="System.Data.SQLite.EF6"/>

    <connectionStrings>
        <add name="TestDb" connectionString="Data Source=TestDb.db" providerName="System.Data.SQLite.EF6"/>
    </connectionStrings>

    name="TestDb" 指定这条连接字符串的名称为"TestDb", 用在自定义的数据库上下文类中

    connectionString="Data Source=TestDb.db" 指定数据源为"TestDb.db", 即数据库文件名为"TestDb.db",默认保存路径为工作目录(可自己指定其它路径)

    providerName="System.Data.SQLite.EF6" 指定数据提供器

    3. 数据库上下文类

    例:(注意其中的数据库连接字符串的使用方法)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.Entity;
    using SQLite.CodeFirst;
    using System.Data.Entity.ModelConfiguration.Conventions; namespace WindowsFormsApplication_sqlite2 { class TestDbContext :DbContext { //base("TestDb")调用基类构造函数,可指定连接字符串名称 public TestDbContext() : base("TestDb") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { //base.OnModelCreating(modelBuilder); //关闭所有级联删除 modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<TestDbContext>(modelBuilder); Database.SetInitializer(sqliteConnectionInitializer); } public DbSet<TestA> TestAs { get; set; } public DbSet<TestB> TestBs { get; set; } } class TestA { public long Id { get; set; } public string Barcode { get; set; } public string Name { get; set; } } class TestB { public long Id { get; set; } public long TestAId { get; set; } public DateTime Date { get; set; } [ForeignKey("TestAId")] public TestA TestA { get; set; } } }
  • 相关阅读:
    Apache Ant 1.9.1 版发布
    Apache Subversion 1.8.0rc2 发布
    GNU Gatekeeper 3.3 发布,网关守护管理
    Jekyll 1.0 发布,Ruby 的静态网站生成器
    R语言 3.0.1 源码已经提交到 Github
    SymmetricDS 3.4.0 发布,数据同步和复制
    beego 0.6.0 版本发布,Go 应用框架
    Doxygen 1.8.4 发布,文档生成工具
    SunshineCRM 20130518发布,附带更新说明
    Semplice Linux 4 发布,轻量级发行版
  • 原文地址:https://www.cnblogs.com/gmcn/p/5833994.html
Copyright © 2020-2023  润新知