我主要将dbcontext与以下语句一起使用:
using (var context = new MyContext())
{
}
但是我后来不得不添加一个具有更改数据库功能的项目。我发现我可以将dbcontext构造函数更改为:
public MyContext(string connectionstring)
: base(connectionstring)
{
}
我为连接字符串创建了一个带有属性的类:
public static class DbAccessor
{
public static string ConnectionStringForContext { get; set; }
}
我在开始时设置了此属性,而我的using语句如下所示:
using (var context = new MyContext(DbAccessor.ConnectionStringForContext)
{}
它可以工作,但是我的连接字符串现在无处不在,我觉得我不应该使用连接字符串来做到这一点。有更好的方法吗?如果要更改连接字符串,最好的方法是什么?我应该停止使用这些using语句吗?
我已经看到了这个问题:实体框架在运行时更改连接
但是不同之处在于,我有一个有效的解决方案,但我不想到处都有我的连接字符串。如果我在每个using语句中使用了该扩展方法。几乎就像我的解决方案在每个using语句中仅多一行...
您可以在上下文中尝试使用连接字符串的静态工厂方法(或您喜欢的工厂类),如下所示:
public class MyContext : ...
{
public MyContext(string connectionstring)
: base(connectionstring)
{
}
public static MyContext Create()
{
return new MyContext(DbAccessor.ConnectionStringForContext);
}
}
然后您可以像这样创建上下文:
using (var context = MyContext.Create())
{
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句