C# Entity Framework框架 Code First 模式 连接 SQL\Access\SQLite (组合式)

Web.config 配置文件很重要,有些蒙圈,自己稍微整理了下。看起来就简单些。

步骤一:

NuGet 给项目安装 Entity Framework。

步骤二:

NuGet给项目安装 JetEntityFrameworkProvider

步骤三:

添加数据库位置Web.config

<connectionStrings>
<!--Access--> <add name="AccessContext" connectionString="Provider=Microsoft.ACE.OleDb.12.0;Data Source=|DataDirectory|\AccessDataBase.accdb" providerName="JetEntityFrameworkProvider" />
<!--SQLite--> <add name="sqliteContext" connectionString="Data Source=|DataDirectory|\Sqlite.db3;" providerName="System.Data.SQLite.EF6" />
<!--SQL--> <add name="SqlContext" connectionString="server=.;database=demo;uid=sa;pwd=only" providerName="System.Data.SqlClient" /> </connectionStrings>

步骤四:

Web.config添加节点

复制代码
<providers>
<!--SQL--> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<!--Access--> <provider invariantName="JetEntityFrameworkProvider" type="JetEntityFrameworkProvider.JetProviderServices, JetEntityFrameworkProvider" />
<!--SQLite--> <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
<!--SQLite-->
<provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6"/>
</providers>
复制代码

步骤五:

创建连库文件

复制代码
public partial class BlContext : DbContext
    {
//可改为其他连接 或 动态
public BlContext() : base("SqlContext") { } public BlContext(string connectionName) : base(connectionName) { } public virtual DbSet<Entity.User> User { get; set; } }
复制代码

声明:ACCESS数据库,创建的数据库中会自动根据实体类创建表,无需手动添加,修改列属性未测试。

OK.目前为止EF框架可适应连接Access\SQLite\SQL数据库的Code First 模式。

不喜勿喷,谢谢合作。

 

补充:

在使用ACCESS数据库时,更新表结构的时候如果出现以下字样(不懂英文)

System.InvalidOperationException:“The model backing the 'BlContext' context has changed since the database was created. Consider using Code 

如果出现这种字样的时候需要在Global.asax中添加以下代码:

protected void Application_Start(object sender, EventArgs e)
{
   Database.SetInitializer<DataBase.BlContext>(null);
}

这样就可以随意修改表结构喽。

 

posted @   鞍山老菜鸟  阅读(2103)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示