C# .Net ef(Entity Framework 6) SQLite配置使用(codefirst)

简介
本文主要介绍在.Net(C#)中,使用Entity Framework 操作Sqlite数据库,并且通过codefirst实现自动创建SQLite数据库和表,以及一些常用操作和配置。

1、项目中需要安装SQLite相关Nuget包

项目名上右键 =》点击"管理Nuget程序包" =》搜索"System.Data.SQLite" =》点击 “System.Data.SQLite(x86/x64)” 、“System.Data.SQLite EF6”、“System.Data.SQLite LINQ” 这3个包进行安装。

搜索"SQLite.CodeFirst" =》点击安装

确保以下Nuget包都已安装:

System.Data.SQLite(x86/x64)
System.Data.SQLite EF6
System.Data.SQLite LINQ
SQLite.CodeFirst
Entity Framework 

2、项目中代码

1)新建ORMContext类继承DbContext

using SQLite.CodeFirst;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UtilityWeb.ORM.Models;
namespace UtilityWeb.ORM
{
    public class ORMContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<ORMContext>(modelBuilder);
            Database.SetInitializer(sqliteConnectionInitializer);
        }
        public ORMContext() : base("ORMContext") { } //配置使用的连接名
        public DbSet<EmployInfo> EmployInfos { get; set; }
        public DbSet<DeptInfo> DeptInfos { get; set; }
    }
}

2)用到的Model类DeptInfo和EmployInfo

public class EmployInfo
    {
        public string DeptName { get; set; }
        public string EmployName { get; set; }
        public string Gender { get; set; }
        [Key]
        public string UserCode { get; set; }
        public int RuleCode { get; set; }
        public int OrderCode { get; set; }
    }
    public class DeptInfo
    {
        public string SubDept { get; set; }
        public string DeptName { get; set; }
        public string DeptCode { get; set; }
        public string RuleCode { get; set; }
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int DeptId { get; set; }
    }

说明:[key]是配置主键,[DatabaseGenerated(DatabaseGeneratedOption.Identity)]配置自增主键

3)使用操作示例代码

public static void AddDeptInfo(DeptInfo m)
        {
            using (ORMContext db = new ORMContext())
            {
                var model = db.DeptInfos.Where(w => w.DeptName.Trim() == m.DeptName.Trim() && w.SubDept.Trim() == m.SubDept.Trim()).FirstOrDefault();
                if (model == null)
                {
                    db.DeptInfos.Add(m);
                    db.SaveChanges();
                    return;
                }
                model.SubDept = m.SubDept.Trim();
                model.DeptName = m.DeptName.Trim();
                model.DeptCode = m.DeptCode.Trim();
                model.RuleCode = m.RuleCode.Trim();
                db.SaveChanges();
            }
        }
        public static void AddUserInfo(EmployInfo u)
        {
            using (ORMContext db = new ORMContext())
            {
                var model = db.EmployInfos.Where(w => w.UserCode == u.UserCode).FirstOrDefault();
                if (model == null)
                {
                    db.EmployInfos.Add(u);
                    db.SaveChanges();
                    return;
                }
                model.UserCode = u.UserCode;
                model.Gender = u.Gender;
                model.EmployName = u.EmployName;
                model.RuleCode = u.RuleCode;
                db.SaveChanges();
            }
        }

3、项目中用到的配置文件

如果出现奇怪的问题,仔细检查一下配置文件中entityFrameworkprovidersDbProviderFactories,自动生成修改的配置文件,有时会有问题,我之前就被坑了。

1)控制台程序配置文件

<?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" />
  </configSections>
  <connectionStrings>
    <add name="ORMContext" connectionString="data source=.\utilityweb.db" providerName="System.Data.SQLite.EF6" />
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <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>
  </entityFramework>
  <system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SQLite.EF6" />
      <add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".Net Framework Data Provider for SQLite"
type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite"/>
      <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>

2)Web网站用到的配置文件

<?xml version="1.0" encoding="utf-8"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=152368
  -->
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    
  </configSections>
  <connectionStrings>
    <add name="ORMContext" connectionString="data source=D:\dbpath\utilityweb.db" providerName="System.Data.SQLite.EF6" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="DbConnectString" value="User Id=BFCSJQ;Password=DHHZDHHZ;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.255.90)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=srvcbzb1)))" />
  </appSettings>
  <system.web>
    <httpRuntime targetFramework="4.5" />
    <compilation debug="true" targetFramework="4.5" />
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <profile defaultProvider="DefaultProfileProvider">
      <providers>
        <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </profile>
    <membership defaultProvider="DefaultMembershipProvider">
      <providers>
        <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <roleManager defaultProvider="DefaultRoleProvider">
      <providers>
        <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </roleManager>
    <!--
            If you are deploying to a cloud environment that has multiple web server instances,
            you should change session state mode from "InProc" to "Custom". In addition,
            change the connection string named "DefaultConnection" to connect to an instance
            of SQL Server (including SQL Azure and SQL  Compact) instead of to SQL Server Express.
      -->
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
      </providers>
    </sessionState>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.3.0.0" newVersion="1.3.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v12.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <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>
  </entityFramework>
  <system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SQLite.EF6" />
      <add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".Net Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
      <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>

了解更多分析及数据抓取可查看:
http://data.yisurvey.com:8989/
特别说明:本文旨在技术交流,请勿将涉及的技术用于非法用途,否则一切后果自负。如果您觉得我们侵犯了您的合法权益,请联系我们予以处理。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 .NET Framework 4.7.2 使用 EF6 DbContext 创建 SQLite 数据库和多张数据表,您可以按照以下步骤操作: 1. 安装 SQLite 数据库引擎和 ADO.NET 数据提供程序。您可以从 SQLite 官网下载 SQLite 数据库引擎和 ADO.NET 数据提供程序的安装文件,然后按照提示进行安装。 2. 在 Visual Studio 中创建一个新的 .NET Framework 项目,选择“类库”作为项目类型。 3. 在“解决方案资源管理器”中,右键单击项目名称,选择“管理 NuGet 程序包”。 4. 在“NuGet 包管理器”中搜索并安装以下两个包: - EntityFramework - System.Data.SQLite 5. 在项目中添加一个新的类文件,命名为“MyDbContext.cs”。 6. 在“MyDbContext.cs”文件中,定义一个继承自“DbContext”的类,并添加以下代码: ```csharp using System.Data.Entity; public class MyDbContext : DbContext { public MyDbContext() : base("name=MyDbContext") { } public DbSet<Table1> Table1 { get; set; } public DbSet<Table2> Table2 { get; set; } } ``` 在上面的代码中,“Table1”和“Table2”是您需要创建的数据表的实体类,它们应该与数据库中的表对应。 7. 创建实体类“Table1.cs”和“Table2.cs”,并在其中定义数据表的结构。例如: ```csharp public class Table1 { [Key] public int Id { get; set; } public string Name { get; set; } } ``` 在上面的代码中,“Id”是主键,它会自动递增,您可以添加其他属性。 8. 在“App.config”文件中添加以下配置: ```xml <configuration> <connectionStrings> <add name="MyDbContext" connectionString="Data Source=MyDatabase.sqlite" providerName="System.Data.SQLite" /> </connectionStrings> </configuration> ``` 在上面的配置中,“MyDatabase.sqlite”是您要创建的 SQLite 数据库的名称。 9. 在“Program.cs”文件中添加以下代码,以创建数据库并初始化数据表: ```csharp using System.Data.Entity; class Program { static void Main(string[] args) { Database.SetInitializer<MyDbContext>(new CreateDatabaseIfNotExists<MyDbContext>()); using (var context = new MyDbContext()) { context.Database.Initialize(false); } } } ``` 在上面的代码中,“SetInitializer”方法设置了数据表的初始化策略,这里我们使用“CreateDatabaseIfNotExists”策略,表示如果数据库不存在,则创建一个新的数据库。然后,通过“Initialize”方法初始化数据库和数据表。 10. 运行程序,您应该能够在 SQLite 数据库中看到创建的数据表。 以上就是在 .NET Framework 4.7.2 中使用 EF6 DbContext 创建 SQLite 数据库和多张数据表的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值