本文整理汇总了C#中DbContext.OpenConnection方法的典型用法代码示例。如果您正苦于以下问题:C# DbContext.OpenConnection方法的具体用法?C# DbContext.OpenConnection怎么用?C# DbContext.OpenConnection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DbContext
的用法示例。
在下文中一共展示了DbContext.OpenConnection方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AppLock
/// <summary>
/// Initializes a new instance of the <see cref="AppLock" /> class.
/// </summary>
/// <param name="db">The database.</param>
/// <param name="lockResourceName">The lock resource.</param>
/// <param name="disposeDbContext">if set to <c>true</c> dispose the database context when the AppLock is disposed.</param>
public AppLock(
DbContext db,
string lockResourceName,
bool disposeDbContext = true)
{
disposables = Disposable.Create(OnDispose);
this.db = db;
this.lockResourceName = lockResourceName;
this.disposeDbContext = disposeDbContext;
connection = (DbConnection) db.OpenConnection();
const string cmd = @"
DECLARE @result int;
EXEC @result = sp_getapplock @Resource = @lockResource,
@LockMode = 'Exclusive',
@LockOwner = 'Session',
@LockTimeout = 60000;
SELECT @result";
var result = -1000;
using (var getAppLock = connection.CreateCommand())
{
getAppLock.Parameters.Add(new SqlParameter("lockResource", lockResourceName));
getAppLock.CommandText = cmd;
try
{
Debug.WriteLineIf(WriteDebugOutput, $"Trying to acquire app lock '{lockResourceName}' (#{GetHashCode()})");
result = (int) getAppLock.ExecuteScalar();
}
catch (SqlException exception)
when (exception.Message.StartsWith("Timeout expired."))
{
Debug.WriteLineIf(WriteDebugOutput, $"Timeout expired waiting for sp_getapplock. (#{GetHashCode()})");
DebugWriteLocks();
return;
}
}
resultCode = result;
if (result >= 0)
{
Debug.WriteLineIf(WriteDebugOutput, $"Acquired app lock '{lockResourceName}' with result {result} (#{GetHashCode()})");
}
else
{
Debug.WriteLineIf(WriteDebugOutput, $"Failed to acquire app lock '{lockResourceName}' with code {result} (#{GetHashCode()})");
}
#if DEBUG
Active[this] = this;
#endif
}