using Microsoft.Data.SqlClient;
using System;
using System.Collections;
using System.Data;
namespace Kean.Infrastructure.Database
{
///
/// 基于 Dapper 的 SQL Server 连接上下文
///
internal sealed class MssqlDapperContext : IDbContext
{
private readonly Hashtable _cache = new();
///
/// 构造函数
///
/// 数据库连接字符串
internal MssqlDapperContext(string connectionString) => Connection = new SqlConnection(connectionString);
public IDbConnection Connection { get; }
public IDbTransaction Transaction { get; private set; }
public ISchema From()
where T : IEntity
=> From(null);
public ISchema From(string name = null)
where T : IEntity
{
var key = name ?? typeof(T).Name;
if (_cache.ContainsKey(key))
{
return _cache[key] as ISchema;
}
else
{
var schema = new MssqlDapperSchema(this, name);
_cache.Add(key, schema);
return schema;
}
}
public ISchema From()
where T1 : IEntity
where T2 : IEntity
=> From(null, null);
public ISchema From(string name1 = null, string name2 = null)
where T1 : IEntity
where T2 : IEntity
{
var key = $"{name1 ?? typeof(T1).Name}&{name2 ?? typeof(T2).Name}";
if (_cache.ContainsKey(key))
{
return _cache[key] as ISchema;
}
else
{
var schema = new MssqlDapperSchema(this, name1, name2);
_cache.Add(key, schema);
return schema;
}
}
public ISchema From()
where T1 : IEntity
where T2 : IEntity
where T3 : IEntity
=> From(null, null, null);
public ISchema From(string name1 = null, string name2 = null, string name3 = null)
where T1 : IEntity
where T2 : IEntity
where T3 : IEntity
{
var key = $"{name1 ?? typeof(T1).Name}&{name2 ?? typeof(T2).Name}&{name3 ?? typeof(T3).Name}";
if (_cache.ContainsKey(key))
{
return _cache[key] as ISchema;
}
else
{
var schema = new MssqlDapperSchema(this, name1, name2, name3);
_cache.Add(key, schema);
return schema;
}
}
string IDbConnection.ConnectionString
{
get => Connection.ConnectionString;
set => Connection.ConnectionString = value;
}
int IDbConnection.ConnectionTimeout => Connection.ConnectionTimeout;
string IDbConnection.Database => Connection.Database;
ConnectionState IDbConnection.State => Connection.State;
IDbTransaction IDbConnection.BeginTransaction() => Transaction = Connection.BeginTransaction();
IDbTransaction IDbConnection.BeginTransaction(IsolationLevel il) => Transaction = Connection.BeginTransaction(il);
void IDbConnection.ChangeDatabase(string databaseName) => Connection.ChangeDatabase(databaseName);
void IDbConnection.Close() => Connection.Close();
IDbCommand IDbConnection.CreateCommand() => Connection.CreateCommand();
void IDbConnection.Open() => Connection.Open();
void IDisposable.Dispose() => Connection.Dispose();
}
}