C# 如何在使用db上下文时指定连接字符串
我正在使用EF的存储库模式,遇到了一个问题,即我无法通过变量为C# 如何在使用db上下文时指定连接字符串,c#,entity-framework,C#,Entity Framework,我正在使用EF的存储库模式,遇到了一个问题,即我无法通过变量为DbContext设置连接字符串。目前,我的构造函数是无参数的(它必须符合模式),即 IUnitOfWork uow=newunitofwork(); DeviceService DeviceService=新设备服务(uow); var what=deviceService.GetAllDevices(); 公共工作单元() { _ctx=新的TContext(); _存储库=新字典(); _已处理=错误; } EMDataCon
DbContext
设置连接字符串。目前,我的构造函数是无参数的(它必须符合模式),即
IUnitOfWork uow=newunitofwork();
DeviceService DeviceService=新设备服务(uow);
var what=deviceService.GetAllDevices();
公共工作单元()
{
_ctx=新的TContext();
_存储库=新字典();
_已处理=错误;
}
EMDataContext
用于在其构造函数中获取一个字符串来定义连接字符串
,但不能再这样做了,因此当以这种方式创建EMDataContext
时,我如何实际告诉它连接到什么?您的问题可以重写为“如何使用new()
约束将参数传递给泛型类型构造函数”
发件人:
新约束指定泛型类中的任何类型参数
声明必须具有公共无参数构造函数
由于裸实体框架上下文不包含无参数构造函数,我假设您的EMDataContext
是从中派生的自定义上下文:
public class EMDataContext : DbContext
{
// parameterless ctor, since you're using new() in UnitOfWork<TContext>
public EMDataContext() : base(???)
{
}
public EMDataContext(string connectionString) : base(connectionString)
{
}
}
或者(如果您仍然想“适应模式”),尝试使用Activator
实例化上下文:
public class UnitOfWork<TContext>
{
public UnitOfWork(string connectionString)
{
_ctx = (TContext)Activator.CreateInstance(typeof(TContext), new[] { connectionString });
}
}
公共类UnitOfWork
{
公共工作单元(字符串连接字符串)
{
_ctx=(TContext)Activator.CreateInstance(typeof(TContext),new[]{connectionString});
}
}
newunitofwork()中发生了什么?是否需要连接到多个数据库?如果不需要,请使用web.config或app.config文件。@JensKloster Updated.ta-目前还没有,问题是如何传入连接字符串?@Chris ok。TContext
?它是否继承了允许您设置连接字符串的内容?此外,.config文件是如果不直接指定connectionstring.EF的位置,它将在那里找到。
public class UnitOfWork<TContext>
{
public UnitOfWork(TContext ctx)
{
_ctx = ctx;
}
}
public class UnitOfWork<TContext>
{
public UnitOfWork(string connectionString)
{
_ctx = (TContext)Activator.CreateInstance(typeof(TContext), new[] { connectionString });
}
}