我有混合 EF 和普通 SQL 调用的代码。整个事情在Azure上运行,所以我们使用ReliableSqlConnection 。 我们正在使用 TransactionScope,但没有分布式事务管理器(又是 Azure)。因此我必须将 ReliableSqlConnection 传递给每个 SQL 调用。
现在的问题是如何将 ReliableSqlConnection 传递到 EF 调用中?
如果发现这篇文章:
How to use ADO.net Entity Framework with an existing SqlConnection?
这会导致以下代码:
MetadataWorkspace workspace = new MetadataWorkspace(
new string[] { "res://*/" },
new Assembly[] { Assembly.GetExecutingAssembly() });
using (var scope = new TransactionScope())
using (var conn = DatabaseUtil.GetConnection())
using (EntityConnection entityConnection = new EntityConnection(workspace, (DbConnection)conn))
using (var db = new UniversalModelEntities(entityConnection))
{
//Do EF things
//Call other SQL commands
return db.SaveChanges();
}
但是我无法将 ReliableSqlConnection 转换为 DbConnection,UniversalModelEntities 也不接受 EntityConnection。
最佳答案
问题是 ReliableSqlConnection
实现 IDbConnection
接口(interface),但 EF 上下文构造函数都接受 DbConnection
(不是接口(interface))。我不知道他们为什么做出这样的决定,也许他们背后有合理的理由,也许这只是糟糕的设计决定。然而,你必须忍受这一点。请注意,使用 ReliableSqlConnection.Open()
或 ReliableSqlConnection.Current
返回的任何内容都不是一个选项 - 它会起作用,但您将只使用常规连接,然后无需重试逻辑,基本上绕过了整个 ReliableSqlConnection 类的目的。相反,您可以尝试围绕 ReliableSqlConnection 创建一个包装器,如下所示:
public class ReliableSqlConnectionWrapper : DbConnection {
private readonly ReliableSqlConnection _connection;
public ReliableSqlConnectionWrapper(ReliableSqlConnection connection) {
_connection = connection;
}
protected override DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel) {
return (DbTransaction) _connection.BeginTransaction();
}
public override void Close() {
_connection.Close();
}
public override void ChangeDatabase(string databaseName) {
_connection.ChangeDatabase(databaseName);
}
public override void Open() {
_connection.Open();
}
public override string ConnectionString
{
get { return _connection.ConnectionString; }
set { _connection.ConnectionString = value; }
}
public override string Database
{
get { return _connection.Database; }
}
public override ConnectionState State
{
get { return _connection.State; }
}
public override string DataSource
{
get { return _connection.Current?.DataSource; }
}
public override string ServerVersion
{
get { return _connection.Current?.ServerVersion; }
}
protected override DbCommand CreateDbCommand() {
return _connection.CreateCommand();
}
protected override DbProviderFactory DbProviderFactory {
get { return SqlClientFactory.Instance; }
}
}
这里,我们按照 EF 的要求继承了 DbConnection
,并将所有逻辑转发到底层 ReliableSqlConnection
实例。请注意,您可能需要重写 DbConnection
中的更多方法(例如 Dispose
) - 此处我仅展示如何仅重写必需的(抽象)成员。
包装器的替代选项是复制 ReliableSqlConnection
类的源代码并修改它以继承 DbConnection
。
然后,在 EF 上下文中,您需要添加一个接受 DbConnection 的构造函数:
public UniversalModelEntities(DbConnection connection, bool contextOwnsConnection) : base(connection, contextOwnsConnection) {}
这只是使用相同的参数调用基类构造函数。第二个参数 (contextOwnsConnection
) 定义上下文是否能够管理此连接,例如在释放上下文时关闭它。
如果您使用 EF 数据库优先方法 - 编辑为您的上下文生成代码的 EF 模板,并在其中添加此构造函数。
完成这一切之后,您可以执行以下操作:
using (var scope = new TransactionScope()) {
using (var conn = new ReliableSqlConnection("")) {
using (var ctx = new UniversalModelEntities(new ReliableSqlConnectionWrapper(conn), false)) {
}
}
}
经过一番调查,我得出的结论是,上述方法可能很难实现,因为连接包装器与 Entity Framework 不太兼容。考虑更简单的替代方案 - 使用 DbCommandInterceptor 并通过提供 ReliableSqlConnection 的同一 transient 故障处理程序库提供的扩展方法重用重试逻辑:
public class RetryInterceptor : DbCommandInterceptor {
public override void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext) {
interceptionContext.Result = ((SqlCommand)command).ExecuteNonQueryWithRetry();
}
public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext) {
interceptionContext.Result = ((SqlCommand)command).ExecuteReaderWithRetry();
}
public override void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext) {
interceptionContext.Result = ((SqlCommand)command).ExecuteScalarWithRetry();
}
}
因此,我们拦截命令并将其执行转发到 transient 故障处理程序 block 。然后在main方法中:
static void Main() {
// don't forget to add interceptor
DbInterception.Add(new RetryInterceptor());
MetadataWorkspace workspace = new MetadataWorkspace(
new string[] {"res://*/"},
new[] {Assembly.GetExecutingAssembly()});
// for example
var strategy = new FixedInterval("fixed", 10, TimeSpan.FromSeconds(3));
var manager = new RetryManager(new[] {strategy}, "fixed");
RetryManager.SetDefault(manager);
using (var scope = new TransactionScope()) {
using (var conn = new ReliableSqlConnection("data source=(LocalDb)\\v11.0;initial catalog=TestDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework")) {
// pass Current - we don't need retry logic from ReliableSqlConnection any more
using (var ctx = new TestDBEntities(new EntityConnection(workspace, conn.Current), false)) {
// some sample code I used for testing
var code = new Code();
code.Name = "some code";
ctx.Codes.Add(code);
ctx.SaveChanges();
scope.Complete();
}
}
}
}
关于c# - 对 EntityFramework 和 "normal"SQL 调用使用相同的 SqlConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36940240/