为动态连接字符串设置实体框架 [英] Setup Entity Framework For Dynamic Connection String
问题描述
我正在开发一个应用程序,该应用程序将在多个数据库中使用相同的数据库架构.为此,我创建了一个名为 MyTemplate
的数据库.创建新用户时,他们将拥有自己的数据库实例.因此,将创建一个名为 MyTemplate_[UserName]
之类的数据库.当用户登录时,我需要将他们的查询指向他们的数据库.出于这个原因,我知道我需要在运行时设置连接字符串.我的问题是,我也想使用实体框架.
I am working on an app that will use the same database schema across multiple databases. For this reason, I've created a database called MyTemplate
. When a new user is created, they will have their own instance of the database. So, a database called something like MyTemplate_[UserName]
will be created. When a user logs in, I need to point their queries to their database. For this reason, I know that I need to set the connection string at runtime. My problem is, I also want to use the Entity Framework.
目前,我使用 MyTemplate 作为源创建了一个新的 .edmx.我以为我可以更新代码并在那里设置连接字符串.不幸的是,我不知道如何设置它.TemplateEntities 的构造函数没有允许我传入连接字符串的重载.我注意到从 DbContext 派生的 TemplateEntities,我认为这不是问题.
Currently, I created a new .edmx using MyTemplate as the source. I thought I would be able to update the code and set the connection string there. Unfortunately, I can't figure out how to set it. The constructor to TemplateEntities does not have an overload that allows me to pass in a connection string. I noticed that TemplateEntities derived from DbContext, I don't think this would be the problem.
string connectionString = GetUsersConnectionString();
using (TemplateEntities entities = new TemplateEntities())
{
TemplateEntity entity = new TemplateEntity();
// Save to the database
entities.TemplateEntity.Add(entity);
entities.SaveChanges();
}
我是否错误地创建了 .edmx
?还是我完全错过了什么?我谷歌显示的所有内容都应该允许传入连接字符串的重载.但是,我没有可用的重载.
Am I creating the .edmx
incorrectly? Or am I missing something entirely? Everything I Google shows an overload that should allow a connection string passed in. However, I don't have that overload available.
推荐答案
生成的 TemplateEntities
类被标记为 partial
.
The generated TemplateEntities
class is marked as partial
.
您所要做的就是添加另一个文件,其中包含部分类定义的另一部分,该部分公开了您要使用的构造函数:
All you have to do is add another file with another part of the partial class definition that exposes the constructor you want to use:
partial class TemplateEntities
{
public TemplateEntities( string nameOrConnectionString )
: base( nameOrConnectionString )
{
}
}
然后将您的连接字符串传递给此构造函数.
Then pass your connection string in to this constructor.
您想将此代码放在不同的文件中,以便在您更新 edmx 模型时不会被覆盖.
You want to put this code in a different file so it doesn't get over-written when you update your edmx model.
这篇关于为动态连接字符串设置实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!