加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在使用db context时指定连接字符串

发布时间:2020-12-15 05:39:35 所属栏目:百科 来源:网络整理
导读:我正在使用EF的存储库模式,并遇到了一个问题,我无法弄清楚如何通过变量设置DbContext的连接字符串.目前我的构造函数是无参数的(它必须符合他的模式),即 IUnitOfWork uow = new UnitOfWorkEMDataContext();DeviceService deviceService = new DeviceService(u
我正在使用EF的存储库模式,并遇到了一个问题,我无法弄清楚如何通过变量设置DbContext的连接字符串.目前我的构造函数是无参数的(它必须符合他的模式),即
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 });
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读