public virtual void Setup() { string connectionString = string.Format("Data Source=.\\dapperTest_{0}.sqlite", Guid.NewGuid()); string[] connectionParts = connectionString.Split(';'); string file = connectionParts .ToDictionary(k => k.Split('=')[0], v => v.Split('=')[1]) .Where(d => d.Key.Equals("Data Source", StringComparison.OrdinalIgnoreCase)) .Select(k => k.Value).Single(); if (File.Exists(file)) { File.Delete(file); } SQLiteConnection connection = new SQLiteConnection(connectionString); var config = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new SqliteDialect()); var sqlGenerator = new SqlGeneratorImpl(config); Db = new Database(connection, sqlGenerator); var files = new List <string> { ReadScriptFile("CreateAnimalTable"), ReadScriptFile("CreateFooTable"), ReadScriptFile("CreateMultikeyTable"), ReadScriptFile("CreatePersonTable"), ReadScriptFile("CreateCarTable") }; foreach (var setupFile in files) { connection.Execute(setupFile); } }
private static IDatabase SQLite() { try { var dbFile = AppConfigUtility.AppDirectory + AppConfigUtility.DatabaseName; if (!File.Exists(dbFile)) { throw new DatabaseNotFoundException(); } lock (Locker) { if (_instance != null) { return(_instance); } var connectionString = AppConfigUtility.DatabaseConnString; var connection = new SQLiteConnection(connectionString); var config = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new SqliteDialect()); var sqlGenerator = new SqlGeneratorImpl(config); _instance = new Database(connection, sqlGenerator); } return(_instance); } catch (Exception ex) { LogUtility.Log(LogUtility.LogType.SystemError, MethodBase.GetCurrentMethod().Name, ex.Message); throw new Exception("Erro ao instanciar o banco de dados"); //TODO: put on resource file } }
/// <summary> /// Dapper.Ext /// </summary> /// <param name="dbType"></param> /// <param name="dbConnect"></param> /// <returns></returns> public static IDatabase CreateDb(DbType dbType, string dbConnect) { IDbConnection connection = null; IDatabase dbDatabase = null; var config = new DapperExtensionsConfiguration(); switch (dbType) { case DbType.SqlServer: connection = new SqlConnection(dbConnect); config = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new SqlServerDialect()); break; case DbType.MySql: connection = new MySqlConnection(dbConnect); config = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new MySqlDialect()); break; } var sqlGenerator = new SqlGeneratorImpl(config); dbDatabase = new Database(connection, sqlGenerator); return(dbDatabase); }
private void BuildDatabaseContext() { switch (_dbType) { case DbDialect.SqlServer: var connection = new SqlConnection(_connectionString); var config = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new SqlServerDialect()); var sqlGenerator = new SqlGeneratorImpl(config); DatabaseSession = new Database(connection, sqlGenerator); break; case DbDialect.Oracle: break; case DbDialect.PostgreSql: break; case DbDialect.SqlCe: break; case DbDialect.Sqlite: break; case DbDialect.MySqlDialect: var mysqlConnection = new MySqlConnection(_connectionString); var mysqlConfig = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new MySqlDialect()); var mysqlGenerator = new MySqlGenerator(mysqlConfig); DatabaseSession = new Database(mysqlConnection, mysqlGenerator); break; default: break; } }
/// <summary> /// 打开映射扩展对象 /// </summary> public void OpenMapExt() { var config = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new SqlServerDialect()); var sqlGenerator = new SqlGeneratorImpl(config); _iDb = new Database(_conn, sqlGenerator);; }
public void DoesNotPrefixColumnListWithTableName() { Mock <IMemberMap> property1 = new Mock <IMemberMap>(); property1.SetupGet(p => p.KeyType).Returns(KeyType.Identity).Verifiable(); Mock <IMemberMap> property2 = new Mock <IMemberMap>(); property2.SetupGet(p => p.KeyType).Returns(KeyType.NotAKey).Verifiable(); property2.SetupGet(p => p.Name).Returns("Name").Verifiable(); property2.SetupGet(p => p.ColumnName).Returns("Name").Verifiable(); List <IMemberMap> properties = new List <IMemberMap> { property1.Object, property2.Object }; ClassMap.SetupGet(c => c.Properties).Returns(properties).Verifiable(); ClassMap.SetupGet(c => c.TableName).Returns("TableName"); Dialect.Setup(c => c.GetTableName(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns <string, string, string>((a, b, c) => b); Dialect.Setup(d => d.GetColumnName(It.IsAny <string>(), It.IsAny <string>(), null)).Returns <string, string, string>((a, b, c) => a + (a == null ? String.Empty : ".") + b); SqlGeneratorImpl generator = new SqlGeneratorImpl(Configuration.Object); var sql = generator.Insert(ClassMap.Object); Assert.AreEqual("INSERT INTO TableName (Name) VALUES (@i_1)", sql); }
/// <summary> /// DapperExtensions 没有实现一对多 /// // 多表联查在这个库里没有提供,多表联查的话可以自己用Dapper的Query<T>(TFirst, TSecond, TResult,...)这个方法来实现 /// </summary> /// <returns></returns> public IEnumerable <TestPersonEntity> TestDapperExtensions() { // Map 文件 TestPersonEntityMapper SqlConnection connection = new SqlConnection(connectionString); var config = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new SqlServerDialect()); // new List<Assembly>() --> Count =0 var sqlGenerator = new SqlGeneratorImpl(config); Db = new Database(connection, sqlGenerator); // 拼接条件 查询 IList <IPredicate> predList = new List <IPredicate>(); predList.Add(Predicates.Field <TestEntity>(p => p.Name, Operator.Like, "A%")); predList.Add(Predicates.Field <TestEntity>(p => p.Id, Operator.Eq, 2)); IPredicateGroup predGroup = Predicates.Group(GroupOperator.And, predList.ToArray()); var ret1 = Db.GetList <TestEntity>(predGroup); var ret2 = Db.GetList <TestPersonEntity>(); connection.Close(); return(ret2); //TestEntity p2 = Db.Get<TestEntity>(1); //return p2.Address; }
/// <summary> /// 批量插入功能 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="entityList"></param> public void InsertBatch(IDbConnection conn, IEnumerable <T> entityList, IDbTransaction transaction = null) { #region 补全 过滤Ignore字段(可以过滤mapping类里面设置的ignore) var tblName = string.Format("dbo.{0}", typeof(T).Name); var tran = (SqlTransaction)transaction; using (var bulkCopy = new SqlBulkCopy(conn as SqlConnection, SqlBulkCopyOptions.TableLock, tran)) { bulkCopy.BatchSize = entityList.Count(); bulkCopy.DestinationTableName = tblName; var table = new DataTable(); DapperExtensions.Sql.ISqlGenerator sqlGenerator = new SqlGeneratorImpl(new DapperExtensionsConfiguration()); var classMap = sqlGenerator.Configuration.GetMap <T>(); var props = classMap.Properties.Where(x => x.Ignored == false).ToArray(); foreach (var propertyInfo in props) { bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name); table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyInfo.PropertyType) ?? propertyInfo.PropertyInfo.PropertyType); } var values = new object[props.Count()]; foreach (var itemm in entityList) { for (var i = 0; i < values.Length; i++) { values[i] = props[i].PropertyInfo.GetValue(itemm, null); } table.Rows.Add(values); } bulkCopy.WriteToServer(table); } #endregion }
private void Init(DbType dbType) { ISqlDialect dialect = null; switch (dbType) { case DbType.SQLServer: dialect = new SqlServerDialect(); break; case DbType.Oracle: dialect = new OracleDialect(); break; case DbType.DB2: dialect = new DB2DialectCustom(); break; case DbType.MySQL: dialect = new MySqlDialect(); break; default: throw new NotSupportedException("dbType"); } Config = new IdentityServerDapperExtensionsConfiguration(this, dialect); SqlGenerator = new SqlGeneratorImpl(Config); Db = new Database(Connection, SqlGenerator); }
protected override void CommonSetup(DbConnection connection, SqlDialectBase sqlDialect) { var config = DapperAsyncExtensions.Configure(typeof(AutoClassMapper <>), new List <Assembly>(), sqlDialect); var sqlGenerator = new SqlGeneratorImpl(config); Db = new AsyncDatabase(connection, sqlGenerator); }
public static IDatabase GetDatabase(string key, DataBaseType type) { var connectionString = System.Configuration.ConfigurationManager.AppSettings[key]; if (string.IsNullOrEmpty(connectionString)) { throw new ArgumentException("数据库连接字符串不能为空!"); } IDbConnection cnn = null; IDapperExtensionsConfiguration config = null; switch (type) { case DataBaseType.Orcale: config = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new OracleDialect()); cnn = new Oracle.ManagedDataAccess.Client.OracleConnection(connectionString); break; case DataBaseType.SqlServer: config = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new SqlServerDialect()); cnn = new System.Data.SqlClient.SqlConnection(connectionString); break; default: throw new NotImplementedException("尚未实现对该数据库的支持!"); } var sqlGenerator = new SqlGeneratorImpl(config); return(new Database(cnn, sqlGenerator)); }
//protected IKardSession KardSession { get; set; } protected IDatabase GetDb() { var connection = GetConnection(); var sqlGenerator = new SqlGeneratorImpl(_dapperConfig); IDatabase _db = new Database(connection, sqlGenerator); return(_db); }
public IDatabase GetDatabase() { var connection = new SqlConnection("Integrated Security=False;server=192.168.0.101;database=WALIUJR_SYS;User ID=sa;Password=Cst-88888;Connect Timeout=30"); var config = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new SqlServerDialect()); var sqlGenerator = new SqlGeneratorImpl(config); return(new Database(connection, sqlGenerator)); }
public IDatabase CreateConnection() { var connection = new MySqlConnection(DataSettingsManager.MySqlConnectionString); var config = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new MySqlDialect()); var sqlGenerator = new SqlGeneratorImpl(config); return(new Database(connection, sqlGenerator)); }
private void InitDB() { var config = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new OracleDialect()); var sqlGenerator = new SqlGeneratorImpl(config); connection = new OracleConnection(this.connstr); Db = new Database(connection, sqlGenerator); }
public DapperHelper(string conn) { var orcalConn = new OracleConnection(conn); var orcaleconfig = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new OracleDialect()); var orcaleGenerator = new SqlGeneratorImpl(orcaleconfig); Connection = new Database(orcalConn, orcaleGenerator); Cmd.Connection = orcalConn; }
public IDapperAsyncImplementor LoadAsync(DatabaseType dbType, IDatabase db) { SqlGeneratorImpl sqlGenerator = GetSqlGeneratorImpl(dbType); _dapper = new DapperAsyncImplementor(sqlGenerator, db); return(_dapper); }
/// <summary> /// 构造函数 /// </summary> /// <param name="transaction">事务</param> /// <param name="connection"></param> protected RepositoryBase(IDbTransaction transaction, IDbConnection connection) { Transaction = transaction as DbTransaction; Connection = connection as DbConnection; DapperExtensions.DapperExtensions.SqlDialect = new MySqlDialect(); this.DefaultSort = "ASC"; DapperConfig = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new MySqlDialect()); SqlGenerator = new SqlGeneratorImpl(DapperConfig); }
private IDatabase CreateDatabase() { var config = new DapperExtensionsConfiguration( _dapperOptionsBuilder.DefaultMapper, _dapperOptionsBuilder.MapperAssemblies, _dapperOptionsBuilder.SqlDialect); var sqlGenerator = new SqlGeneratorImpl(config); return(new Database(_dapperOptionsBuilder.GetDbConnection(), sqlGenerator)); }
public MySqlOperator(DataBaseName databaseName, List <Assembly> mappingAssemblies = null) : base(databaseName) { _mappingAssemblies = mappingAssemblies ?? new List <Assembly>() { Assembly.GetCallingAssembly() }; var config = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), _mappingAssemblies, new MySqlDialect()); SqlGenerator = new SqlGeneratorImpl(config); }
public OracleDataAccess(string connectionName) { string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[connectionName].ConnectionString; dbConnection = new OracleConnection(connectionString); var config = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new OracleDialect()); var sqlGenerator = new SqlGeneratorImpl(config); dbExtention = new Database(dbConnection, sqlGenerator); }
public SQLServerDataAccess(string connectionName = "DefaultConnection") { string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[connectionName].ConnectionString; dbConnection = new System.Data.SqlClient.SqlConnection(connectionString); var config = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new SqlServerDialect()); var sqlGenerator = new SqlGeneratorImpl(config); dbExtention = new Database(dbConnection, sqlGenerator); }
public IDapperImplementor Load(DatabaseType dbType, IDatabase db) { SqlGeneratorImpl sqlGenerator = GetSqlGeneratorImpl(dbType); #if ASYNC _dapper = new DapperAsyncImplementor(sqlGenerator, db); #else _dapper = new DapperImplementor(sqlGenerator, db); #endif return(_dapper); }
public IDatabase GetDatabase() { #if NETSTANDARD2_0 var tableConfigList = JsonConfigurationHelper.GetAppSettings <List <TableConfiguration> >("TableConfigCollection"); var tableConfigEntity = tableConfigList.Where(q => q.Name == _dbName).Select(q => q.ConnectString).FirstOrDefault(); #elif NET45 var tableConfigList = JsonConfigurationHelper.GetAppSettings <TableConfiguration>(); var tableConfigEntity = tableConfigList.Where(q => q.Name == _dbName).Select(q => q.ConnectString).FirstOrDefault(); #endif var connection = new SqlConnection(tableConfigEntity); var config = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new SqlServerDialect()); var sqlGenerator = new SqlGeneratorImpl(config); return(new Database(connection, sqlGenerator)); }
public void Test() { IDapperExtensionsConfiguration conf = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new MySqlDialect()); SqlGeneratorImpl sqlGeneratorImpl = new SqlGeneratorImpl(conf); IFieldPredicate nameFieldPredicate = Predicates.Field <User>(p => p.Name, Operator.Like, "不知道%"); List <ISort> sortList = new List <ISort>(); sortList.Add(Predicates.Sort <User>(u => u.Id)); string selectPagedSql = sqlGeneratorImpl.SelectPaged(new UserMapper(), nameFieldPredicate, sortList, 20, 2, new Dictionary <string, object>()); string res = "SELECT `User`.`Id`, `User`.`Name`, `User`.`Psw`, `User`.`RoleId` FROM `User` WHERE (`User`.`Name` LIKE @Name_0) ORDER BY `User`.`Id` ASC LIMIT @firstResult, @maxResults"; Assert.Equal(selectPagedSql, res); }
public void MySQLBuildTest() { IDapperExtensionsConfiguration conf = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new MySqlDialect()); SqlGeneratorImpl sqlGeneratorImpl = new SqlGeneratorImpl(conf); IFieldPredicate nameFieldPredicate = Predicates.Field <User>(p => p.Name, Operator.Like, "уе%"); string namesql = nameFieldPredicate.GetSql(sqlGeneratorImpl, new Dictionary <string, object>()); Assert.Equal("(`User`.`Name` LIKE @Name_0)", namesql); List <string> valueList = new List <string>() { "1", "2", "3" }; IFieldPredicate nameFieldPredicate2 = Predicates.Field <User>(p => p.Name, Operator.Eq, valueList); string namesql2 = nameFieldPredicate2.GetSql(sqlGeneratorImpl, new Dictionary <string, object>()); Assert.Equal("(`User`.`Name` IN (@Name_0, @Name_1, @Name_2))", namesql2); IBetweenPredicate idFieldPredicate = Predicates.Between <User>(p => p.Name, new BetweenValues { Value1 = 1, Value2 = 10 }, true); string idsql = idFieldPredicate.GetSql(sqlGeneratorImpl, new Dictionary <string, object>()); Assert.Equal("(`User`.`Name` NOT BETWEEN @Name_0 AND @Name_1)", idsql); IPropertyPredicate propertyPredicate = Predicates.Property <User, Role>(u => u.RoleId, Operator.Eq, r => r.Id, true); string propertysql = propertyPredicate.GetSql(sqlGeneratorImpl, new Dictionary <string, object>()); Assert.Equal("(`User`.`RoleId` <> `Role`.`Id`)", propertysql); IExistsPredicate existsPredicate = Predicates.Exists <User>(nameFieldPredicate, true); string existssql = existsPredicate.GetSql(sqlGeneratorImpl, new Dictionary <string, object>()); Assert.Equal("(NOT EXISTS (SELECT 1 FROM `User` WHERE (`User`.`Name` LIKE @Name_0)))", existssql); IList <IPredicate> predList = new List <IPredicate> { nameFieldPredicate, idFieldPredicate }; IPredicateGroup predGroup1 = Predicates.Group(GroupOperator.And, predList.ToArray()); IList <IPredicate> predList2 = new List <IPredicate> { predGroup1, existsPredicate }; IPredicateGroup predGroup2 = Predicates.Group(GroupOperator.Or, predList2.ToArray()); string groupsql = predGroup2.GetSql(sqlGeneratorImpl, new Dictionary <string, object>()); string res = "(((`User`.`Name` LIKE @Name_0) AND (`User`.`Name` NOT BETWEEN @Name_1 AND @Name_2)) OR (NOT EXISTS (SELECT 1 FROM `User` WHERE (`User`.`Name` LIKE @Name_3))))"; Assert.Equal(groupsql, res); }
/// <inheritdoc /> public IDatabase GetDatabase() { if (_database == null) { var dapperOptions = _iocResolver.Resolve <DapperOptionsBuilder>(); var config = new DapperExtensionsConfiguration( dapperOptions.DefaultMapper, dapperOptions.MapperAssemblies, dapperOptions.SqlDialect); var sqlGenerator = new SqlGeneratorImpl(config); _database = new Database(dapperOptions.GetDbConnection(), sqlGenerator); } return(_database); }
public IDatabase Build(string ConnectionName) { //this.ConnectionName = ConnectionName; DbConnectionConfig dbconfig = Config.Connections.FirstOrDefault(m => m.Name.ToLower() == ConnectionName.ToLower()); if (dbconfig.IsNotNull()) { var config = new CissyDapperConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new K()); var sqlGenerator = new SqlGeneratorImpl(config); T dbconnection = new T(); dbconnection.ConnectionString = dbconfig.GetConnectionString(); return(new DB(dbconnection, sqlGenerator)); } return(default(IDatabase)); }
public IDatabase Create() { //var config = new DapperExtensionsConfiguration(typeof(AutoClassMapper<>), new List<Assembly>(), new SqlServerDialect()); var config = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), _sqlDialect); config.ThrowIfArgumentIsNull("dapperConfiguration"); var sqlGenerator = new SqlGeneratorImpl(config); var database = new Database(_dbConnection, sqlGenerator); database.ThrowIfArgumentIsNull("Database"); return(database); }
private Database CreateDatabase() { ISqlDialect sqlDialect = null; IDbConnection connection = null; switch (_dataBaseType.ToLower()) { case "mysql": { connection = new MySqlConnection(_connectionString); sqlDialect = new MySqlDialect(); } break; case "sqlserver": { connection = new SqlConnection(_connectionString); sqlDialect = new SqlServerDialect(); } break; case "oracle": { } break; case "sqlite": { //connection = new SQLiteConnection(_connectionString); sqlDialect = new SqliteDialect(); } break; default: break; } var config = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), sqlDialect); var sqlGenerator = new SqlGeneratorImpl(config); //if (connection.State != ConnectionState.Open) // connection.Open(); return(new Database(connection, sqlGenerator)); }