动态连接字符串的安装实体框架 [英] Setup Entity Framework For Dynamic Connection String
问题描述
MyTemplate
的数据库。当创建新用户时,他们将拥有自己的数据库实例。因此,将创建一个称为 MyTemplate_ [UserName]
的数据库。当用户登录时,我需要将其查询指向其数据库。因此,我知道我需要在运行时设置连接字符串。我的问题是,我也想使用实体框架。 目前,我使用MyTemplate作为源创建了一个新的.edmx。我以为我可以更新代码并将连接字符串设置在那里。不幸的是,我不知道如何设置它。 TemplateEntities的构造函数不具有允许我传递连接字符串的重载。我注意到从DbContext派生的TemplateEntities,我不认为这将是问题。
string connectionString = GetUsersConnectionString();
使用(TemplateEntities entities = new TemplateEntities())
{
TemplateEntity entity = new TemplateEntity();
//保存到数据库
entities.TemplateEntity.Add(entity);
entities.SaveChanges();
}
我创建了 .edmx
不正确?还是我完全缺少一些东西?所有我显示的一个重载应该允许一个连接字符串传入。但是,我没有这个重载可用。
生成的 TemplateEntities
类标记为 partial
。
所有你需要做的是添加另一个文件与部分类定义的另一部分暴露您要使用的构造函数:
partial class TemplateEntities
{
public TemplateEntities(string nameOrConnectionString)
:base(nameOrConnectionString)
{
}
}
然后将连接字符串传递给此构造函数。
将此代码放在不同的文件中,以便在您更新edmx模型时不会被覆盖。
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.
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();
}
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.
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.
You want to put this code in a different file so it doesn't get over-written when you update your edmx model.
这篇关于动态连接字符串的安装实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!