IUnitOfWork uow = new UnitOfWork<EMDataContext>();DeviceService deviceService = new DeviceService(uow);var what = deviceService.GetAllDevices();public UnitOfWork(){ _ctx = new TContext(); _repositorIEs = new Dictionary<Type,object>(); _disposed = false;}
EMDataContext用于在其构造函数中获取一个字符串来定义ConnectionString但是不能再这样做了,那么如何以这种方式实际告诉EMDataContext要连接的内容呢?
解决方法 您的问题可以重写为“如何将参数传递给具有new()约束的泛型类型构造函数”.从MSDN开始:
The new constraint specifIEs that any type argument in a generic class
declaration must have a public parameterless constructor.
由于裸实体框架上下文不包含无参数构造函数,因此我假设您的EMDataContext是从中派生的自定义上下文:
public class EMDataContext : DbContext{ // parameterless ctor,since you're using new() in UnitOfWork<TContext> public EMDataContext() : base(???) { } public EMDataContext(string connectionString) : base(connectionString) { }}
现在,我认为您的EMDataContext无法使用无参数构造函数,因此也无法使用new()约束,尤其是当您说您确实要传递连接字符串参数时.
尝试更改UnitOfWork以接受其构造函数中已初始化的上下文(常见模式):
public class UnitOfWork<TContext>{ public UnitOfWork(TContext ctx) { _ctx = ctx; }}
或者(如果您仍想“适应模式”),尝试使用Activator实例化上下文:
public class UnitOfWork<TContext>{ public UnitOfWork(string connectionString) { _ctx = (TContext)Activator.CreateInstance(typeof(TContext),new[] { connectionString }); }}总结
以上是内存溢出为你收集整理的c# – 如何在使用db context时指定连接字符串全部内容,希望文章能够帮你解决c# – 如何在使用db context时指定连接字符串所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)