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

2023-12-04 09:04

本文主要是介绍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和EmployInfopublic 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 instanceof 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>

这篇关于C#.Net EF(Entity Framework 6) SQLite配置使用(codefirst)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/452899

相关文章

C#借助Spire.XLS for .NET实现在Excel中添加文档属性

《C#借助Spire.XLSfor.NET实现在Excel中添加文档属性》在日常的数据处理和项目管理中,Excel文档扮演着举足轻重的角色,本文将深入探讨如何在C#中借助强大的第三方库Spire.... 目录为什么需要程序化添加Excel文档属性使用Spire.XLS for .NET库实现文档属性管理Sp

python中的flask_sqlalchemy的使用及示例详解

《python中的flask_sqlalchemy的使用及示例详解》文章主要介绍了在使用SQLAlchemy创建模型实例时,通过元类动态创建实例的方式,并说明了如何在实例化时执行__init__方法,... 目录@orm.reconstructorSQLAlchemy的回滚关联其他模型数据库基本操作将数据添

Spring配置扩展之JavaConfig的使用小结

《Spring配置扩展之JavaConfig的使用小结》JavaConfig是Spring框架中基于纯Java代码的配置方式,用于替代传统的XML配置,通过注解(如@Bean)定义Spring容器的组... 目录JavaConfig 的概念什么是JavaConfig?为什么使用 JavaConfig?Jav

Spring Boot Interceptor的原理、配置、顺序控制及与Filter的关键区别对比分析

《SpringBootInterceptor的原理、配置、顺序控制及与Filter的关键区别对比分析》本文主要介绍了SpringBoot中的拦截器(Interceptor)及其与过滤器(Filt... 目录前言一、核心功能二、拦截器的实现2.1 定义自定义拦截器2.2 注册拦截器三、多拦截器的执行顺序四、过

Java使用Spire.Doc for Java实现Word自动化插入图片

《Java使用Spire.DocforJava实现Word自动化插入图片》在日常工作中,Word文档是不可或缺的工具,而图片作为信息传达的重要载体,其在文档中的插入与布局显得尤为关键,下面我们就来... 目录1. Spire.Doc for Java库介绍与安装2. 使用特定的环绕方式插入图片3. 在指定位

Springboot3 ResponseEntity 完全使用案例

《Springboot3ResponseEntity完全使用案例》ResponseEntity是SpringBoot中控制HTTP响应的核心工具——它能让你精准定义响应状态码、响应头、响应体,相比... 目录Spring Boot 3 ResponseEntity 完全使用教程前置准备1. 项目基础依赖(M

springboot的controller中如何获取applicatim.yml的配置值

《springboot的controller中如何获取applicatim.yml的配置值》本文介绍了在SpringBoot的Controller中获取application.yml配置值的四种方式,... 目录1. 使用@Value注解(最常用)application.yml 配置Controller 中

springboot中配置logback-spring.xml的方法

《springboot中配置logback-spring.xml的方法》文章介绍了如何在SpringBoot项目中配置logback-spring.xml文件来进行日志管理,包括如何定义日志输出方式、... 目录一、在src/main/resources目录下,也就是在classpath路径下创建logba

Java使用Spire.Barcode for Java实现条形码生成与识别

《Java使用Spire.BarcodeforJava实现条形码生成与识别》在现代商业和技术领域,条形码无处不在,本教程将引导您深入了解如何在您的Java项目中利用Spire.Barcodefor... 目录1. Spire.Barcode for Java 简介与环境配置2. 使用 Spire.Barco

Android使用java实现网络连通性检查详解

《Android使用java实现网络连通性检查详解》这篇文章主要为大家详细介绍了Android使用java实现网络连通性检查的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录NetCheck.Java(可直接拷贝)使用示例(Activity/Fragment 内)权限要求