• 【转发】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);
    }

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

    转自:https://www.cnblogs.com/OleRookie/p/8567153.html

  • 相关阅读:
    在VMWare虚拟机下的ubuntu中Samba服务的安装
    Shell表达式,如${file##*/}
    如何从官网下载QT
    SATA命令之security
    Clip
    JS判断是否在微信浏览器打开
    微信小程序请求数据报错: 如若已在管理后台更新域名配置,请刷新项目配置后重新编译项目,操作路径:“详情-域名信息”
    typeof()和instanceof的用法区别
    javascrip 对数组的操作方法
    微信小程序 修改数据,并动态渲染页面;修改数组;
  • 原文地址:https://www.cnblogs.com/firstcsharp/p/16695336.html
Copyright © 2020-2023  润新知