65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 C#.Net 和 Entity Framework 的 SQLite

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.71/5 (16投票s)

2016年12月2日

CPOL

2分钟阅读

viewsIcon

152606

在C# Winform和控制台应用程序中使用Entity Framework与SQLite数据库的最简单方法

引言

本文介绍如何将 SQLite 数据库与 Entity Framework 一起使用。我写这篇文章是因为我无法使用 SQLite 的 Entity Framework 工具,即来自 sqlite.org 的 Entity Framework 工具在我的系统中无法工作,可能在您的系统中也一样。

您可能已经熟悉 Entity Framework,它是开发人员的最佳工具。这就是我决定写这篇文章的原因。并为我的英语不好道歉 :)

所以在本文中,您将能够将 sqlite 与 Entity Framework 一起使用。

背景

您需要从 Nuget 包管理器获取 System.Data.Sqlite。

输入 PM>Install-Package System.Data.SQLite

然后您需要任何 Sqlite 数据库管理工具。

 

使用代码

创建一个 SQLite 数据库,例如 'SQLiteWithEF.db'

创建一个表

CREATE TABLE EmployeeMaster (

ID INTEGER PRIMARY KEY AUTOINCREMENT

UNIQUE,

EmpName VARCHAR NOT NULL,

Salary DOUBLE NOT NULL,

Designation VARCHAR NOT NULL

);

现在创建一个控制台应用程序并添加对以下项的引用

  1. 来自 Nuget 包管理器的 System.Data.SQLite。
  2. System.Data.Linq

注意:它将在您的 App.Config 文件中创建一些条目。只需删除所有条目,除了默认条目。

现在您的 App.Config 文件将如下所示

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

现在创建一个名为 SQLiteConfiguration.cs 的类并编写一些代码

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Common;
using System.Data.SQLite;
using System.Data.SQLite.EF6;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SQLiteWithEF
{
    public class SQLiteConfiguration : DbConfiguration
    {
        public SQLiteConfiguration()
        {
            SetProviderFactory("System.Data.SQLite", SQLiteFactory.Instance);
            SetProviderFactory("System.Data.SQLite.EF6", SQLiteProviderFactory.Instance);
            SetProviderServices("System.Data.SQLite", (DbProviderServices)SQLiteProviderFactory.Instance.GetService(typeof(DbProviderServices)));
        }
    }
}

注意:您可能在想,为什么我从 App.Config 文件中删除了条目并创建了这个配置类或其他什么... 答案是:通过代码配置 Entity Framework 看起来非常容易。并且 App.Config 文件甚至没有显示任何关于我们正在使用的程序集的建议。

现在为 EmployeeMaster 表创建您的模型类,如下所示

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.Linq.Mapping;
using System.Data.SQLite;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SQLiteWithEF
{
    [Table(Name = "EmployeeMaster")]
    public class EmployeeMaster
    {
        [Column(Name = "ID", IsDbGenerated = true, IsPrimaryKey = true, DbType = "INTEGER")]
        [Key]
        public int ID { get; set; }

        [Column(Name = "EmpName", DbType = "VARCHAR")]
        public string EmpName { get; set; }

        [Column(Name = "Salary", DbType = "DOUBLE")]
        public double Salary { get; set; }

        [Column(Name = "Designation", DbType = "VARCHAR")]
        public string Designation { get; set; }
    }
}

现在创建 DatabaseContext.cs 类,并使用 DbContext 类扩展它,如下所示

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SQLiteWithEF
{
    class DatabaseContext : DbContext
    {
        public DatabaseContext() :
            base(new SQLiteConnection()
            {
                ConnectionString = new SQLiteConnectionStringBuilder() { DataSource = "D:\\Databases\\SQLiteWithEF.db", ForeignKeys = true }.ConnectionString
            }, true)
        {
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            base.OnModelCreating(modelBuilder);
        }

        public DbSet<EmployeeMaster> EmployeeMaster { get; set; }
    }
}

在这里查看连接字符串,您必须通过代码创建连接字符串。如果您打算在 App.Config 文件中创建它,它将不起作用。

由于我们在数据库中只创建了一个表,因此您只看到一个 DbSet 属性。如果您有多个表,那么您必须为数据库中存在的每个表或您的应用程序需要的表编写 DbSet。

现在我们已经创建了我们的 Entity Framework 上下文类。我们现在可以使用它了。

所以转到 Program.cs 文件并尝试通过 Lembda 或 Linq 或两者插入、更新、删除和查询数据。

参见示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SQLiteWithEF
{
    class Program
    {
        static void Main(string[] args)
        {
            DatabaseContext context = new DatabaseContext();
            Console.WriteLine("Enter Employee name");
            string name = Console.ReadLine();
            Console.WriteLine("Enter Salary");
            double salary = Convert.ToDouble(Console.ReadLine());
            Console.WriteLine("Enter Designation");
            string designation = Console.ReadLine();
            EmployeeMaster employee = new EmployeeMaster()
            {
                EmpName = name,
                Designation = designation,
                Salary = salary
            };
            context.EmployeeMaster.Add(employee);
            context.SaveChanges();

            var data = context.EmployeeMaster.ToList();
            foreach (var item in data)
            {
                Console.Write(string.Format("ID : {0}  Name : {1}  Salary : {2}   Designation : {3}{4}", item.ID, item.EmpName, item.Salary, item.Designation, Environment.NewLine));
            }

            Console.ReadKey();
        }
    }
}

现在尝试按 F5 或 Control+F5 运行应用程序并查看结果 :)

关注点

  1. Entity Framework 总是将 ID 列视为主键。如果您已将任何其他列声明为主键,那么您必须使用 [Key] 属性对其进行注释。
<code>System.ComponentModel.DataAnnotations</code>

       2. 将您的 SQLiteConfiguration.cs 文件保存在您的上下文类所在的同一文件夹中。

       3. 您可能会注意到我从 DatabaseContext 类中删除了将表名复数化的约定

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            base.OnModelCreating(modelBuilder);
        }

如果您删除此行,您将得到

System.Data.Entity.Infrastructure.DbUpdateException

      4. 在使用库时,请阅读其许可条款和条件。

历史

目前还没有更新。

© . All rights reserved.