【发布时间】:2017-09-19 22:34:44
【问题描述】:
我有一个带有 EF 和存储库模式的 c# 项目。
对于单个数据库,一切正常,但我有不同的模型,它们与不同的数据库相关,例如 User 模型数据来自控制面板数据库,其他模型也来自不同的数据库。
这里我为项目使用通用存储库模式。现在初始化模型时如何将数据库连接字符串发送到存储库?
这是我的存储库模式:
public class Repository<C,T> : IRepository<T> where T : class where C : DbContext, new()
{
private C _context = new C();
public C context
{
get
{
//if (_context == null)
//{
// _context = new C();
// _context.Database.Connection.ConnectionString = "the new connectionstring";
//}
//return dataContext;
return _context;
}
set { _context = value; }
}
private IDbSet<T> _entities;
private IDbSet<T> Entities
{
get
{
if (_entities == null)
_entities = context.Set<T>();
return _entities;
}
}
这是我的服务类
public class UserService: Repository<DyeingContext,User> , IUserRepository
{
public UserService()
{
DyeingContext d = new DyeingContext(DataBase.ControlPanal);
}
//private readonly IRepository<User> _useRepository = new Repository<User>(new DyeingContext(DataBase.ControlPanal));
}``
这是我的上下文类
public partial class DyeingContext:DbContext
{
public DyeingContext(string pDbName):base(GetTheContext(pDbName))
{
}
public DyeingContext():base()
{
//throw new NotImplementedException();
}
public static string GetTheContext(string pDbName)
{
return ConnectionSettings.GetConnectionStringByDbName(pDbName);
}
}
我无法在此处获取连接字符串
DyeingContext d = new DyeingContext(DataBase.ControlPanal);
它说
通过 system.argumentexception 类型异常的数据库连接
有没有办法将多个连接字符串传递到存储库?
我应该如何以及在哪里初始化我的连接字符串以及如何通过存储库传递它?
【问题讨论】:
-
通过查看异常消息,
DataBase.ControlPanal的值似乎为 null 或空,这就是您得到system.argumentexception的原因。 -
实际上我无法存储连接字符串。我不知道如何将不同的连接字符串传递到存储库以及何时应该初始化连接并将其存储到数据库上下文
-
向我们展示
DataBase.ControlPanal代码 -
Database.ControlPanel 只需给我数据库名称。公共类数据库 { 公共静态字符串 SCM = "SCM";公共静态字符串 ControlPanal = "ControlPanal"; // 数据库名称 } 并且当我初始化 DyeingContext 类时,我在构造函数中创建连接字符串并将其作为数据库上下文的基础。
-
DbContext没有通过连接字符串名称接收数据库名称。如果您的连接字符串键是MyConnectionStringKey,那么您的DataBase.ControlPanal应该返回这样的字符串name=MyConnectionStringKey
标签: asp.net-mvc entity-framework-6 repository-pattern