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

相关文章

Java Lambda表达式的使用详解

《JavaLambda表达式的使用详解》:本文主要介绍JavaLambda表达式的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、前言二、Lambda表达式概述1. 什么是Lambda表达式?三、Lambda表达式的语法规则1. 无参数的Lambda表

Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析

《Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析》InstantiationAwareBeanPostProcessor是Spring... 目录一、什么是InstantiationAwareBeanPostProcessor?二、核心方法解

详解如何使用Python构建从数据到文档的自动化工作流

《详解如何使用Python构建从数据到文档的自动化工作流》这篇文章将通过真实工作场景拆解,为大家展示如何用Python构建自动化工作流,让工具代替人力完成这些数字苦力活,感兴趣的小伙伴可以跟随小编一起... 目录一、Excel处理:从数据搬运工到智能分析师二、PDF处理:文档工厂的智能生产线三、邮件自动化:

Nacos注册中心和配置中心的底层原理全面解读

《Nacos注册中心和配置中心的底层原理全面解读》:本文主要介绍Nacos注册中心和配置中心的底层原理的全面解读,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录临时实例和永久实例为什么 Nacos 要将服务实例分为临时实例和永久实例?1.x 版本和2.x版本的区别

Spring @RequestMapping 注解及使用技巧详解

《Spring@RequestMapping注解及使用技巧详解》@RequestMapping是SpringMVC中定义请求映射规则的核心注解,用于将HTTP请求映射到Controller处理方法... 目录一、核心作用二、关键参数说明三、快捷组合注解四、动态路径参数(@PathVariable)五、匹配请

Java 枚举的基本使用方法及实际使用场景

《Java枚举的基本使用方法及实际使用场景》枚举是Java中一种特殊的类,用于定义一组固定的常量,枚举类型提供了更好的类型安全性和可读性,适用于需要定义一组有限且固定的值的场景,本文给大家介绍Jav... 目录一、什么是枚举?二、枚举的基本使用方法定义枚举三、实际使用场景代替常量状态机四、更多用法1.实现接

springboot项目中使用JOSN解析库的方法

《springboot项目中使用JOSN解析库的方法》JSON,全程是JavaScriptObjectNotation,是一种轻量级的数据交换格式,本文给大家介绍springboot项目中使用JOSN... 目录一、jsON解析简介二、Spring Boot项目中使用JSON解析1、pom.XML文件引入依

Java中的record使用详解

《Java中的record使用详解》record是Java14引入的一种新语法(在Java16中成为正式功能),用于定义不可变的数据类,这篇文章给大家介绍Java中的record相关知识,感兴趣的朋友... 目录1. 什么是 record?2. 基本语法3. record 的核心特性4. 使用场景5. 自定

如何搭建并配置HTTPD文件服务及访问权限控制

《如何搭建并配置HTTPD文件服务及访问权限控制》:本文主要介绍如何搭建并配置HTTPD文件服务及访问权限控制的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、安装HTTPD服务二、HTTPD服务目录结构三、配置修改四、服务启动五、基于用户访问权限控制六、

Python使用Tkinter打造一个完整的桌面应用

《Python使用Tkinter打造一个完整的桌面应用》在Python生态中,Tkinter就像一把瑞士军刀,它没有花哨的特效,却能快速搭建出实用的图形界面,作为Python自带的标准库,无需安装即可... 目录一、界面搭建:像搭积木一样组合控件二、菜单系统:给应用装上“控制中枢”三、事件驱动:让界面“活”