我有以下课程:
public class EFRepository<TContext> : IDisposable where TContext : DbContext, IObjectContextAdapter, new()
{
private TContext context;
public EFRepository(string connectionStringName)
{
context = new TContext();
context.Database.Connection.ConnectionString =
ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
}
}
使用以下连接字符串:
<connectionStrings>
<add name="EntitiesConnection" connectionString="metadata=res://*/EntityModel.csdl|res://*/EntityModel.ssdl|res://*/EntityModel.msl;provider=System.Data.SqlClient;provider connection string="data source=Bob-PC;initial catalog=Entities;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
像这样被召唤:
var Entities = new EFRepository<EntitiesConnection>("EntitiesConnection");
这会在主题行中引发错误。我已经看到使用EntityStringBuilder的解决方案,但Connection属性是只读的。关于如何使这项工作的任何想法?
谢谢,
鲍勃
答案 0 :(得分:3)
DbContext
已经有一个接受连接字符串或名称的构造函数。您是否可以修改现有的上下文类以包含接受连接字符串参数的构造函数并调用base(connectionStringOrName)
?
所以上下文看起来像是:
public class SomeContext : DbContext, IObjectContextAdapter
{
public SomeContext(string connectionStringOrName)
: base (connectionStringOrName)
{
}
// Rest of the implementation...
}
然后EFRepository<TContext>
的构造函数看起来像:
public EFRepository(string connectionStringName)
{
context = new TContext(connectionStringName);
}