• C#(.net)使用Sqlite和EntityFramework (DBFirst)


        文章主要内容翻译自Awesh Vishwakarma的博文文字“SQLite with C#.Net and Entity Framework”。博客地址为点击打开链接,侵删。

        IDE:VS2017

       1. 安装SQLite

        NuGet 命令安装SQLite:PM> Install-Package System.Data.SQLite。或NuGet中搜索“sqlite”安装。如下图。

        安装成功App.config(或Web.config)中有如下配置信息

    1. <startup>
    2. <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client" />
    3. </startup>

        2. 下载安装SQLite Expert Personal 4.2

        SQLite Expert是SQLite的可视化工具。下载地址为:点击打开链接。在SQLite Expert中新建数据库(文件格式为.db或sqlite),并建表。可使用下方的测试SQL语句粘贴至SQLite Expert中执行。

    1. CREATE TABLE EmployeeMaster (
    2. ID INTEGER PRIMARY KEY AUTOINCREMENT
    3. UNIQUE,
    4. EmpName VARCHAR NOT NULL,
    5. Salary DOUBLE NOT NULL,
    6. Designation VARCHAR NOT NULL
    7. );

        3. 将.db文件复制到项目中

            将.db文件复制到项目的对应目录中。在文件的属性中“Copy to Output Directory”选择复制。

        4. 写相关类代码

         4.1 创建SQLite数据库配置类SQLiteConfiguration.cs 

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Data.Entity;
    4. using System.Data.Entity.Core.Common;
    5. using System.Data.SQLite;
    6. using System.Data.SQLite.EF6;
    7. using System.Linq;
    8. using System.Text;
    9. using System.Threading.Tasks;
    10. namespace SQLiteWithEF
    11. {
    12. public class SQLiteConfiguration : DbConfiguration
    13. {
    14. public SQLiteConfiguration()
    15. {
    16. SetProviderFactory("System.Data.SQLite", SQLiteFactory.Instance);
    17. SetProviderFactory("System.Data.SQLite.EF6", SQLiteProviderFactory.Instance);
    18. SetProviderServices("System.Data.SQLite", (DbProviderServices)SQLiteProviderFactory.Instance.GetService(typeof(DbProviderServices)));
    19. }
    20. }
    21. }

         4.2 写实体类(以EmployeeMaster为例)    

    1. using System;
    2. using System.Collections.Generic;
    3. using System.ComponentModel.DataAnnotations;
    4. using System.Data.Entity;
    5. using System.Data.Entity.ModelConfiguration.Conventions;
    6. using System.Data.Linq.Mapping;
    7. using System.Data.SQLite;
    8. using System.Diagnostics;
    9. using System.Linq;
    10. using System.Text;
    11. using System.Threading.Tasks;
    12. namespace SQLiteWithEF
    13. {
    14. [Table(Name = "EmployeeMaster")]
    15. public class EmployeeMaster
    16. {
    17. [Column(Name = "ID", IsDbGenerated = true, IsPrimaryKey = true, DbType = "INTEGER")]
    18. [Key]
    19. public int ID { get; set; }
    20. [Column(Name = "EmpName", DbType = "VARCHAR")]
    21. public string EmpName { get; set; }
    22. [Column(Name = "Salary", DbType = "DOUBLE")]
    23. public double Salary { get; set; }
    24. [Column(Name = "Designation", DbType = "VARCHAR")]
    25. public string Designation { get; set; }
    26. }
    27. }

         4.3 新建类似于DbContext的类DataBaseContext

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Data.Entity;
    4. using System.Data.Entity.ModelConfiguration.Conventions;
    5. using System.Data.SQLite;
    6. using System.IO;
    7. using System.Linq;
    8. using System.Text;
    9. using System.Threading.Tasks;
    10. using BoilerCalculator.Entity.CarbonOxidationRate;
    11. namespace BoilerCalculator.EntityFramwork
    12. {
    13.     class DatabaseContext : DbContext
    14.     {
    15.         public DatabaseContext() : base(new SQLiteConnection() {
    16.             ConnectionString = new SQLiteConnectionStringBuilder()
    17.             {
    18.                 DataSource = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Db\BoilerCalculator.db"),
    19.                 ForeignKeys = true
    20.             }.ConnectionString
    21.         }, true)
    22.         {
    23.         }
    24.         protected override void OnModelCreating(DbModelBuilder modelBuilder)
    25.         {
    26.             modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    27.             base.OnModelCreating(modelBuilder);
    28.         }
    29.         
    30.         public DbSet<EmployeeMaster> EmployeeMaster { get; set; }
    31.     }
    32. }

        至此所有配置、数据库连接类已完毕,可在其他类中使用DataBaseContext做类似于EntityFramework对数据库的Lambda Linq操作。以下以Program为例。    

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Text;
    5. using System.Threading.Tasks;
    6. namespace SQLiteWithEF
    7. {
    8. class Program
    9. {
    10. static void Main(string[] args)
    11. {
    12. DatabaseContext context = new DatabaseContext();
    13. Console.WriteLine("Enter Employee name");
    14. string name = Console.ReadLine();
    15. Console.WriteLine("Enter Salary");
    16. double salary = Convert.ToDouble(Console.ReadLine());
    17. Console.WriteLine("Enter Designation");
    18. string designation = Console.ReadLine();
    19. EmployeeMaster employee = new EmployeeMaster()
    20. {
    21. EmpName = name,
    22. Designation = designation,
    23. Salary = salary
    24. };
    25. context.EmployeeMaster.Add(employee);
    26. context.SaveChanges();
    27. var data = context.EmployeeMaster.ToList();
    28. foreach (var item in data)
    29. {
    30. Console.Write(string.Format("ID : {0} Name : {1} Salary : {2} Designation : {3}{4}", item.ID, item.EmpName, item.Salary, item.Designation, Environment.NewLine));
    31. }
    32. Console.ReadKey();
    33. }
    34. }
    35. }

       

        


     

    Unable to load DLL 'SQLite.Interop.dll': The specified module could not be found. (Exception from HR...

  • 相关阅读:
    Laravel Vuejs 实战:开发知乎 (21)前后端分离 API token 认证
    Laravel Vuejs 实战:开发知乎 (20)使用 Vuejs 组件化
    Laravel Vuejs 实战:开发知乎 (18-19)用户关注问题
    Laravel Vuejs 实战:开发知乎 (17)实现提交答案
    Laravel Vuejs 实战:开发知乎 (16)创建问题的答案 Answer
    Laravel Vuejs 实战:开发知乎 (15)问题 Feed 和删除问题
    Laravel Vuejs 实战:开发知乎 (13)实现编辑问题
    Laravel Vuejs 实战:开发知乎 (12)使用 Repository 模式
    Laravel Vuejs 实战:开发知乎 (11)实现选择话题整个流程
    Jmeter函数作用域实时取值覆盖[针对HTTP Request等控制器]
  • 原文地址:https://www.cnblogs.com/owenzh/p/13177089.html
Copyright © 2020-2023  润新知