我会提供我为解决这个问题所做的完整实现(基于gandjustas的提示)。我编写了一个简单的上下文包装器,可以按以下方式使用:
using (var wrapper = new ContextWrapper<VNKEntities>())
{
}
ContextWrapper
类型是一个模板,它简单地包装了上下文,这个上下文是以稍微不同的方式构建的(仅使用一个连接字符串),然后通过属性公开。它的内部实现如下:
public class ContextWrapper<TContext> : IDisposable
where TContext : ObjectContext
{
private TContext _context;
private EntityConnectionManager _manager;
private bool _disposed;
public ContextWrapper()
: this(true)
{
}
public ContextWrapper(bool lazyLoadingEnabled)
{
_disposed = false;
_manager = new EntityConnectionManager();
_context = (TContext)Activator.CreateInstance(typeof(TContext), _manager.Connection);
_context.ContextOptions.LazyLoadingEnabled = lazyLoadingEnabled;
}
~ContextWrapper()
{
Dispose(false);
}
public TContext Context
{
get { return _context; }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (_manager != null)
{
_manager.Dispose();
_manager = null;
}
var ctx = _context as IDisposable;
if (ctx != null)
{
ctx.Dispose();
_context = null;
}
}
}
_disposed = true;
}
}
你可以看到自定义类
EntityConnectionManager
的用法:
internal class EntityConnectionManager : IDisposable
{
private DbConnection _connection;
private EntityConnection _entityConnection;
private volatile bool _disposed;
public EntityConnectionManager()
{
var workspace = new MetadataWorkspace(Setting.MetadataWorkspacePaths.Split('|'), new[] { Assembly.ReflectionOnlyLoad(Setting.MetadataAssemblyNameToConsider) });
_connection = new SqlConnection(Setting.ConnectionString);
_entityConnection = new EntityConnection(workspace, _connection);
_disposed = false;
}
public EntityConnection Connection
{
get { return _entityConnection; }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (_connection != null)
{
_connection.Dispose();
_connection = null;
}
if (_entityConnection != null)
{
_entityConnection.Dispose();
_entityConnection = null;
}
}
}
_disposed = true;
}
}
现在您可以拥有一个连接字符串:
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=localhost;user id=user;pwd=pass;initial catalog=VNK;Pooling=False;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>
并且元数据在应用程序设置部分定义(第二个关键点指向实际存储您域模型的程序集):
<appSettings>
<add key="MetadataWorkspacePaths" value="res://*/VNKModel.csdl|res://*/VNKModel.ssdl|res://*/VNKModel.msl" />
<add key="MetadataAssemblyNameToConsider" value="VNK.Models" />
</appSettings>
Setting
类型的逻辑很简单,它只是从配置文件中提取设置。