实体框架6在代码中设置连接字符串 [英] Entity Framework 6 set connection string in code

查看:81
本文介绍了实体框架6在代码中设置连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Entity Framework 6执行某些数据库操作的dll。我使用的是数据库优先方法。
该模型以及与实体框架有关的所有内容(例如App.config中的连接字符串)都是通过Visual Studio中的向导创建的。

I have a dll that uses the Entity Framework 6 to do some database operations. I'm using a database first approach. The model and everything concerning the Entity Framework, like the connection string in the App.config, were created via the wizzard in Visual Studio.

所以我编译了dll,并将其与相应的.config放到使用该dll的应用程序期望它的文件夹中。

So I compiled the dll and put it together with the corresponding .config in the folder where the application using the dll expects it.

一切正常,直到达到实际值为止进行数据库调用。出现错误:

Everything works fine until I get to the point where an actual database call is made. There I get the error:


找不到MyDatabaseEntity的连接字符串

Cannot find connection string for MyDatabaseEntity

如我所说,自动生成的连接字符串位于dll的配置文件中。我无法更改应用程序的App.config。
但是应用程序移交了一个对象,该对象具有我自己建立连接字符串所需的所有信息。
因此,我正在寻找一种无需依赖配置文件即可在代码中设置连接字符串的方法。
我为数据库优先方法找到的所有教程都使用此方法。
我在这里找到了一条帖子,说在创建对象之类的时候简单地给出连接字符串作为参数

The automatically generated connectionstring is, as I said, in the config file of the dll. I cannot change the App.config of the application. But the application hands over an object that has all the information I need to build the connection string myself. So I'm looking for a way to set the connection string in the code without relying on a config file. All the tutorials I find for a database first approach use this method though. I found a post here that says to simply give the connection string as a parameter when creating the Object like

MyDatabaseEntities = new MyDatabaseEntities(dbConnect);

但是 MyDatabaseEntities没有使用任何参数的构造函数

but ´MyDatabaseEntities´ doesn't have a constructor that takes any parameters

public partial class MyDatabaseEntities : DbContext
{
    public MyDatabaseEntities()
        : base("name=MyDatabaseEntities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<MyTable> MyTable { get; set; }
}


推荐答案

如何:

public partial class MyDatabaseEntities : DbContext
{
public MyDatabaseEntities(string connectionString)
    : base(connectionString)
{
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    throw new UnintentionalCodeFirstException();
}

public virtual DbSet<MyTable> MyTable { get; set; }

}

然后初始化数据库就像您之前所做的那样:

Then initialize your database like you did before:

string myConnectionString = "...";
MyDatabaseEntities = new MyDatabaseEntities(myConnectionString);

这篇关于实体框架6在代码中设置连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆