/// <summary> /// Internal execute method -- Asynchronously copies command information from the map command /// to the command objects, executes them, and builds the result assembly /// structures needed to return the data reader /// </summary> /// <exception cref="InvalidOperationException">behavior must specify CommandBehavior.SequentialAccess</exception> /// <exception cref="InvalidOperationException">input parameters in the entityCommand.Parameters collection must have non-null values.</exception> internal virtual async Task<DbDataReader> ExecuteAsync( EntityCommand entityCommand, CommandBehavior behavior, CancellationToken cancellationToken) { if (CommandBehavior.SequentialAccess != (behavior & CommandBehavior.SequentialAccess)) { throw new InvalidOperationException(Strings.ADP_MustUseSequentialAccess); } var storeDataReader = await ExecuteStoreCommandsAsync(entityCommand, behavior, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); DbDataReader result = null; // If we actually executed something, then go ahead and construct a bridge // data reader for it. if (null != storeDataReader) { try { var columnMap = CreateColumnMap(storeDataReader, 0); if (null == columnMap) { // For a query with no result type (and therefore no column map), consume the reader. // When the user requests Metadata for this reader, we return nothing. await CommandHelper.ConsumeReaderAsync(storeDataReader, cancellationToken).ConfigureAwait( continueOnCapturedContext: false); result = storeDataReader; } else { var metadataWorkspace = entityCommand.Connection.GetMetadataWorkspace(); var nextResultColumnMaps = GetNextResultColumnMaps(storeDataReader); result = _bridgeDataReaderFactory.Create( storeDataReader, columnMap, metadataWorkspace, nextResultColumnMaps); } } catch { // dispose of store reader if there is an error creating the BridgeDataReader storeDataReader.Dispose(); throw; } } return result; }
/// <summary> /// Execute the store commands, and return IteratorSources for each one /// </summary> internal virtual DbDataReader ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) { var storeProviderCommand = PrepareEntityCommandBeforeExecution(entityCommand); DbDataReader reader = null; try { reader = storeProviderCommand.ExecuteReader(behavior & ~CommandBehavior.SequentialAccess); } catch (Exception e) { // we should not be wrapping all exceptions if (e.IsCatchableExceptionType()) { // we don't wan't folks to have to know all the various types of exceptions that can // occur, so we just rethrow a CommandDefinitionException and make whatever we caught // the inner exception of it. throw new EntityCommandExecutionException(Strings.EntityClient_CommandDefinitionExecutionFailed, e); } throw; } return reader; }
// Private Utilities ----------------------------------------------------------------- private void SetupCustomPartialUpdateCommand(EntityCommand command) { AddParametersFromKey(command, command.TargetEntityInfo.PrimaryKey); foreach (var memberName in command.UpdateMemberNames) { var member = command.TargetEntityInfo.GetMember(memberName); if (member == null) { _log.Error("Member {0} not found in entity {1}, partial update command {2}", memberName, command.TargetEntityInfo.FullName, command.CommandName); continue; } //Skip PK members - forgive programmer if he accidentally includes them into update list if (member.Flags.IsSet(EntityMemberFlags.PrimaryKey)) continue; command.Parameters.Add(new EntityCommandParameter(member)); } }
public EntityEditor() { SelectCommand = new EntityCommand(SelectEntity); ClearCommand = new EntityCommand(SelectEntity); }
private void AddParametersFromKey(EntityCommand command, EntityKeyInfo key) { foreach (var keyMember in key.ExpandedKeyMembers) command.Parameters.Add(new EntityCommandParameter(keyMember.Member)); }
private bool AssignEntityInfo(EntityCommand command) { var entInfo = _model.GetEntityInfo(command.TargetEntityType); if (entInfo == null) { _log.Error("Failed to compile custom command {0}: type {1} is not part of entity model.", command, command.TargetEntityType); return false; } command.TargetEntityInfo = entInfo; command.Area = entInfo.Area; return true; }
public void ProcessCustomCommand(EntityCommand command) { if (command.TargetEntityInfo == null && !AssignEntityInfo(command)) //it is an error - entity info not found return; //Individual processing by command kind switch (command.Kind) { case EntityCommandKind.CustomSelect: case EntityCommandKind.CustomInsert: case EntityCommandKind.CustomUpdate: case EntityCommandKind.CustomDelete: //BuildCustomCommandParameters(command); break; case EntityCommandKind.PartialUpdate: SetupCustomPartialUpdateCommand(command); break; }//switch }
static void Main(string[] args) { Console.WriteLine("====**************** PDF.NET SOD 控制台测试程序 **************===="); Assembly coreAss = Assembly.GetAssembly(typeof(AdoHelper));//获得引用程序集 Console.WriteLine("框架核心程序集 PWMIS.Core Version:{0}", coreAss.GetName().Version.ToString()); Console.WriteLine(); Console.WriteLine(" 应用程序配置文件默认的数据库配置信息:\r\n 当前使用的数据库类型是:{0}\r\n 连接字符串为:{1}\r\n 请确保数据库服务器和数据库是否有效且已经初始化过建表脚本(项目下的2个sql脚本文件),\r\n继续请回车,退出请输入字母 Q ." , MyDB.Instance.CurrentDBMSType.ToString(), MyDB.Instance.ConnectionString); Console.WriteLine("=====Power by Bluedoctor,2015.2.8 http://www.pwmis.com/sqlmap ===="); string read = Console.ReadLine(); if (read.ToUpper() == "Q") { return; } IDataParameter[] paraArr = new IDataParameter[] { MyDB.Instance.GetParameter("P1", 111), MyDB.Instance.GetParameter("P2", "abc'ee<edde/>e"), }; string str = DbParameterSerialize.Serialize(paraArr); Console.WriteLine("测试参数序列化:{0}", str); IDataParameter[] paraArr2 = DbParameterSerialize.DeSerialize(str, MyDB.Instance); Console.WriteLine("测试反序列化成功!"); LocalDbContext localDb = new LocalDbContext(); localDb.CurrentDataBase.RegisterCommandHandle(new TransactionLogHandle()); Table_User user = new Table_User(); user.Name = "zhang san"; user.Height = 1.8f; user.Birthday = new DateTime(1980, 1, 1); user.Sex = true; localDb.Add(user); user.Name = "lisi"; user.Height = 1.6f; user.Birthday = new DateTime(1982, 3, 1); user.Sex = false; localDb.Add(user); Console.WriteLine("测试 生成事务日志 成功!(此操作将写入事务日志信息到数据库中。)"); //var logList = localDb.QueryList<MyCommandLogEntity>(OQL.From(new MyCommandLogEntity()).Select().END); AdoHelper db = MyDB.GetDBHelperByConnectionName("local"); var logList = OQL.From <MyCommandLogEntity>().Select().END.ToList(db); foreach (MyCommandLogEntity log in logList) { var paras = DbParameterSerialize.DeSerialize(log.ParameterInfo, db); int count = db.ExecuteNonQuery(log.CommandText, log.CommandType, paras); Console.WriteLine("执行语句:{0} \r\n 受影响行数:{1}", log.CommandText, count); } Console.WriteLine("测试 运行事务日志 成功!(此操作将事务日志的操作信息回放执行。)"); //写入10000条日志,有缓存,可能不会写完 Console.WriteLine("测试日志写入10000 条信息..."); CommandLog loger = new CommandLog(); for (int t = 0; t <= 1; t++) { System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(WriteLog)); thread.Name = "thread" + t; thread.Start(loger); } loger.Flush(); Console.WriteLine("按任意键继续"); Console.ReadLine(); EntityUser etu = new EntityUser(); ITable_User itu = etu.AsEntity(); DateTime dtt = itu.Birthday; //测试 AdoHelper的并发能力 //for (int i = 0; i < 100; i++) //{ // System.Threading.Thread t = new System.Threading.Thread( // new System.Threading.ParameterizedThreadStart(TestDataSetAndOQL)); // t.Name = "thread "+i; // t.Start(); //} //测试生成列的脚本 EntityCommand ecmd = new EntityCommand(new Table_User(), new SqlServer()); string table_script = ecmd.CreateTableCommand; Console.Write("1,测试 OpenSession 长连接数据库访问..."); TestDataSetAndOQL(null); Console.WriteLine("OK"); // Console.WriteLine("2,测试OQL 转SQL..."); RoadTeam.Model.CS.TbCsEvent CsEvent = new RoadTeam.Model.CS.TbCsEvent(); CsEvent.EventID = 1; OQL oql = OQL.From(CsEvent) .Select(CsEvent.EventCheck, CsEvent.EventCheckInfo, CsEvent.EventCheckor, CsEvent.EventCheckTime) .Where(CsEvent.EventID) .END; Console.WriteLine(oql.ToString()); Console.WriteLine("-----------------------"); RoadTeam.Model.CS.TbCsEvent CsEvent2 = new RoadTeam.Model.CS.TbCsEvent(); CsEvent.EventID = 1; OQL oql2 = OQL.From(CsEvent2) .Select(true, CsEvent2.EventCheck, CsEvent2.EventCheckInfo, CsEvent2.EventCheckor, CsEvent2.EventCheckTime) .Where(CsEvent2.EventID) .END; Console.WriteLine(oql2.ToString()); Console.WriteLine("-----------------------"); Console.WriteLine("OK"); // Console.Write("3,测试实体类动态增加虚拟属性..."); UserModels um1 = new UserModels(); um1.AddPropertyName("TestName"); um1["TestName"] = 123; int testi = (int)um1["TestName"]; um1["TestName"] = "abc"; string teststr = (string)um1["TestName"]; Console.WriteLine("OK"); // Console.Write("4,测试缓存..."); var cache = PWMIS.Core.MemoryCache <EntityBase> .Default; cache.Add("UserModels", um1); var cacheData = cache.Get("UserModels"); cache.Remove("UserModels"); Console.WriteLine("OK"); // Console.Write("5,测试自动创建实体类数据库表..."); AutoCreateEntityTable <LT_Users>(); AutoCreateEntityTable <LT_UserRoles>(); Console.WriteLine("OK"); Console.WriteLine("------------测试暂时停止,回车继续运行------"); Console.ReadLine(); //return; Console.Write("6,测试实体类的外键查询..."); TestEntityFK(); Console.WriteLine("OK"); Console.Write("7,测试实体类批量插入..."); OqlInTest(); Console.WriteLine("OK"); Console.WriteLine("8,测试SOD POCO实体类性能..."); Console.WriteLine("SELECT top 100000 UID,Sex,Height,Birthday,Name FROM Table_User"); for (int i = 0; i < 10; i++) { Console.WriteLine("-------------Testt No.{0}----------------", i + 1); TestPocoQuery(); } Console.WriteLine("--------OK---------------"); Console.Write("9,测试OQL IN 子查询..."); TestInChild(); Console.WriteLine("OK"); //TestFun(1, 2, 3); Console.WriteLine("10,测试泛型 OQL --GOQL"); TestGOQL(); Console.WriteLine("OK"); Console.WriteLine("11,测试OQL 批量更新(带条件更新)..."); UpdateTest(); Console.WriteLine("OK"); Console.WriteLine("12,测试批量数据插入性能...."); //InsertTest(); Console.WriteLine("13,OQL 自连接..."); OqlJoinTest(); // Console.Write("14,根据接口类型,自动创建实体类测试..."); TestDynamicEntity(); Console.WriteLine("OK"); // Console.WriteLine("15,Sql 格式化查询测试( SOD 微型ORM功能)..."); AdoHelper dbLocal = new SqlServer(); dbLocal.ConnectionString = MyDB.Instance.ConnectionString; //DataSet ds = dbLocal.ExecuteDataSet("SELECT * FROM Table_User WHERE UID={0} AND Height>={1:5.2}", 1, 1.80M); /* * 下面的写法过时 * var dataList = dbLocal.GetList(reader => * { * return new * { * UID=reader.GetInt32(0), * Name=reader.GetString(1) * }; * }, "SELECT UID,Name FROM Table_User WHERE Sex={0} And Height>={0:5.2}",1, 1.60); */ var dataList = dbLocal.ExecuteMapper("SELECT UID,Name FROM Table_User WHERE Sex={0} And Height>={1:5.2}", 1, 1.60) .MapToList(reader => new { UID = reader.GetInt32(0), Name = reader.GetString(1) }); Console.WriteLine("OK"); // Console.Write("16,测试属性拷贝..."); V_UserModels vum = new V_UserModels(); vum.BIGTEAM_ID = 123;//可空属性,如果目标对象不是的话,无法拷贝 vum.REGION_ID = 456; vum.SMALLTEAM_ID = 789; UserModels um = vum.CopyTo <UserModels>(); Console.WriteLine("OK"); // Console.Write("17,测试【自定义查询】的实体类..."); UserPropertyView up = new UserPropertyView(); OQL q11 = new OQL(up); OQLOrder order = new OQLOrder(q11); q11.Select() .Where(q11.Condition.AND(up.PropertyName, "=", "总成绩").AND(up.PropertyValue, ">", 1000)) .OrderBy(order.Asc(up.UID)); AdoHelper db11 = MyDB.GetDBHelperByConnectionName("local"); var result = EntityQuery <UserPropertyView> .QueryList(q11, db11); //下面2行不是必须 q11.Dispose(); Console.WriteLine("OK"); //EntityContainer ec = new EntityContainer(q11); //var ecResult = ec.MapToList(() => { // return new { AAA = ec.GetItemValue<int>(0), BBB = ec.GetItemValue<string>(1) }; //}); ///////////////////////////////////////////////////// Console.WriteLine("18,测试实体类【自动保存】数据..."); TestAutoSave(); /////////////////测试事务//////////////////////////////////// Console.WriteLine("19,测试测试事务..."); TestTransaction(); TestTransaction2(); Console.WriteLine("事务测试完成!"); Console.WriteLine("-------PDF.NET SOD 测试全部完成-------"); Console.ReadLine(); }
internal static EntityCommand CreateFilteredCommand(EntityConnection connection, string sql, string orderByClause, EntityStoreSchemaFilterObjectTypes queryTypes, List <EntityStoreSchemaFilterEntry> filters, string[] filterAliases) { EntityCommand command = connection.CreateCommand(); command.CommandType = CommandType.Text; command.CommandTimeout = 0; if (filters.Count == 0) { if (!string.IsNullOrEmpty(orderByClause)) { command.CommandText = sql + Environment.NewLine + orderByClause; } else { command.CommandText = sql; } return(command); } StringBuilder whereClause = new StringBuilder(); foreach (string alias in filterAliases) { StringBuilder allows = new StringBuilder(); StringBuilder excludes = new StringBuilder(); foreach (EntityStoreSchemaFilterEntry entry in filters) { // only apply filters of the correct type if ((queryTypes & entry.Types) == 0) { continue; } if (entry.Effect == EntityStoreSchemaFilterEffect.Allow) { AddFilterEntry(command, allows, alias, entry); } else { Debug.Assert(entry.Effect == EntityStoreSchemaFilterEffect.Exclude, "did you add new value?"); AddFilterEntry(command, excludes, alias, entry); } } if (allows.Length != 0) { if (whereClause.Length != 0) { whereClause.Append(Environment.NewLine); whereClause.Append("AND"); whereClause.Append(Environment.NewLine); } whereClause.Append("("); whereClause.Append(allows); whereClause.Append(")"); } if (excludes.Length != 0) { if (whereClause.Length != 0) { whereClause.Append(Environment.NewLine); whereClause.Append("AND"); whereClause.Append(Environment.NewLine); } whereClause.Append("NOT ("); whereClause.Append(excludes); whereClause.Append(")"); } } // did we end up with a where clause? StringBuilder sqlStatement = new StringBuilder(sql); if (whereClause.Length != 0) { sqlStatement.Append(Environment.NewLine); sqlStatement.Append("WHERE"); sqlStatement.Append(Environment.NewLine); sqlStatement.Append(whereClause); } if (!string.IsNullOrEmpty(orderByClause)) { sqlStatement.Append(Environment.NewLine); sqlStatement.Append(orderByClause); } command.CommandText = sqlStatement.ToString(); return(command); }
/// <summary> /// Return a new <see cref="IEntityCommandModel"/> of supplied <see cref="EntityCommand"/>. /// </summary> public IEntityCommandModel NewEntityCommand(EntityCommand command) { return(entityCommandFactories.TryGetValue(command, out EntityCommandFactoryDelegate factory) ? factory.Invoke() : null); }
public void HandleOrder(EntityCommand entityCommand) //TODO: maybe rename this since in the netclient and server 'HandleFoo' tends to represent handling a network message. (this is from the OrderHandler interface) { NetOutgoingMessage msg = NetPeerObject.CreateMessage(); SendEntityCommand(entityCommand); }
public EntityInBuffer(Entity entity, EntityCommand command) { this.entity = entity; this.command = command; this.componentData = null; }
public EntityInBuffer(Entity entity) { this.entity = entity; this.command = EntityCommand.None; this.componentData = null; }
/// <summary> /// Execute the store commands, and return IteratorSources for each one /// </summary> internal virtual async Task<DbDataReader> ExecuteStoreCommandsAsync( EntityCommand entityCommand, CommandBehavior behavior, CancellationToken cancellationToken) { var storeProviderCommand = PrepareEntityCommandBeforeExecution(entityCommand); DbDataReader reader = null; try { reader = await storeProviderCommand.ExecuteReaderAsync(behavior & ~CommandBehavior.SequentialAccess, cancellationToken) .ConfigureAwait(continueOnCapturedContext: false); } catch (Exception e) { // we should not be wrapping all exceptions if (e.IsCatchableExceptionType()) { // we don't wan't folks to have to know all the various types of exceptions that can // occur, so we just rethrow a CommandDefinitionException and make whatever we caught // the inner exception of it. throw new EntityCommandExecutionException(Strings.EntityClient_CommandDefinitionExecutionFailed, e); } throw; } return reader; }
private EntityCommand AddCommand(string commandName, string description, EntityCommandKind kind, EntityInfo entity, EntityKeyInfo selectKey = null) { var command = new EntityCommand(commandName, description, kind, entity, selectKey); _model.AddCommand(command); return command; }
private DbCommand PrepareEntityCommandBeforeExecution(EntityCommand entityCommand) { if (1 != _mappedCommandDefinitions.Count) { throw new NotSupportedException("MARS"); } var entityTransaction = entityCommand.ValidateAndGetEntityTransaction(); var definition = _mappedCommandDefinitions[0]; var storeProviderCommand = new InterceptableDbCommand(definition.CreateCommand(), entityCommand.InterceptionContext); CommandHelper.SetStoreProviderCommandState(entityCommand, entityTransaction, storeProviderCommand); // Copy over the values from the map command to the store command; we // assume that they were not renamed by either the plan compiler or SQL // Generation. // // Note that this pretty much presumes that named parameters are supported // by the store provider, but it might work if we don't reorder/reuse // parameters. // // Note also that the store provider may choose to add parameters to thier // command object for some things; we'll only copy over the values for // parameters that we find in the EntityCommands parameters collection, so // we won't damage anything the store provider did. var hasOutputParameters = false; // Could be null for some providers, don't remove this check if (storeProviderCommand.Parameters != null) { foreach (DbParameter storeParameter in storeProviderCommand.Parameters) { // I could just use the string indexer, but then if I didn't find it the // consumer would get some ParameterNotFound exeception message and that // wouldn't be very meaningful. Instead, I use the IndexOf method and // if I don't find it, it's not a big deal (The store provider must // have added it). var parameterOrdinal = entityCommand.Parameters.IndexOf(storeParameter.ParameterName); if (-1 != parameterOrdinal) { var entityParameter = entityCommand.Parameters[parameterOrdinal]; // _storeProviderServices will be null if this object was created via // the test constructor - but if so we shouldn't be calling this DebugCheck.NotNull(_storeProviderServices); SyncParameterProperties(entityParameter, storeParameter, _storeProviderServices); if (storeParameter.Direction != ParameterDirection.Input) { hasOutputParameters = true; } } } } // If the EntityCommand has output parameters, we must synchronize parameter values when // the reader is closed. Tell the EntityCommand about the store command so that it knows // where to pull those values from. if (hasOutputParameters) { entityCommand.SetStoreProviderCommand(storeProviderCommand); } return storeProviderCommand; }
/// <summary>Creates a new command combining deferred queries.</summary> /// <returns>The combined command created from deferred queries.</returns> protected DbCommand CreateCommandCombined() { var command = Context.CreateStoreCommand(); var sb = new StringBuilder(); var queryCount = 1; foreach (var query in Queries) { // GENERATE SQL #if EF5 var sql = query.Query.ToTraceString(); var parameters = query.Query.Parameters; // UPDATE parameter name foreach (var parameter in parameters) { var oldValue = parameter.Name; var newValue = string.Concat("Z_", queryCount, "_", oldValue); // CREATE parameter var dbParameter = command.CreateParameter(); dbParameter.ParameterName = newValue; dbParameter.Value = parameter.Value; command.Parameters.Add(dbParameter); // REPLACE parameter with new value sql = sql.Replace("@" + oldValue, "@" + newValue); } #elif EF6 var objectQuery = query.Query; var stateField = objectQuery.GetType().BaseType.GetField("_state", BindingFlags.NonPublic | BindingFlags.Instance); var state = stateField.GetValue(objectQuery); var getExecutionPlanMethod = state.GetType().GetMethod("GetExecutionPlan", BindingFlags.NonPublic | BindingFlags.Instance); var getExecutionPlan = getExecutionPlanMethod.Invoke(state, new object[] { null }); var prepareEntityCommandMethod = getExecutionPlan.GetType().GetMethod("PrepareEntityCommand", BindingFlags.NonPublic | BindingFlags.Instance); string sql = ""; using (EntityCommand entityCommand = (EntityCommand)prepareEntityCommandMethod.Invoke(getExecutionPlan, new object[] { objectQuery.Context, objectQuery.Parameters })) { var getCommandDefinitionMethod = entityCommand.GetType().GetMethod("GetCommandDefinition", BindingFlags.NonPublic | BindingFlags.Instance); var getCommandDefinition = getCommandDefinitionMethod.Invoke(entityCommand, new object[0]); var prepareEntityCommandBeforeExecutionMethod = getCommandDefinition.GetType().GetMethod("PrepareEntityCommandBeforeExecution", BindingFlags.NonPublic | BindingFlags.Instance); var prepareEntityCommandBeforeExecution = (DbCommand)prepareEntityCommandBeforeExecutionMethod.Invoke(getCommandDefinition, new object[] { entityCommand }); sql = prepareEntityCommandBeforeExecution.CommandText; var parameters = prepareEntityCommandBeforeExecution.Parameters; // UPDATE parameter name foreach (DbParameter parameter in parameters) { var oldValue = parameter.ParameterName; if (oldValue.StartsWith("@")) { oldValue = oldValue.Substring(1); } var newValue = string.Concat("Z_", queryCount, "_", oldValue); // CREATE parameter var dbParameter = command.CreateParameter(); dbParameter.ParameterName = newValue; dbParameter.Value = parameter.Value; command.Parameters.Add(dbParameter); // REPLACE parameter with new value sql = sql.Replace("@" + oldValue, "@" + newValue); } } #elif EFCORE RelationalQueryContext queryContext; var queryCommand = query.CreateExecutorAndGetCommand(out queryContext); var sql = queryCommand.CommandText; var parameters = queryCommand.Parameters; // UPDATE parameter name foreach (var parameter in queryContext.ParameterValues) { var oldValue = parameter.Key; var newValue = string.Concat("Z_", queryCount, "_", oldValue); // CREATE parameter var dbParameter = command.CreateParameter(); dbParameter.ParameterName = newValue; dbParameter.Value = parameter.Value; command.Parameters.Add(dbParameter); // REPLACE parameter with new value sql = sql.Replace("@" + oldValue, "@" + newValue); } #endif sb.AppendLine(string.Concat("-- EF+ Query Future: ", queryCount, " of ", Queries.Count)); sb.AppendLine(sql); sb.Append(";"); // SQL Server, SQL Azure, MySQL sb.AppendLine(); sb.AppendLine(); queryCount++; } command.CommandText = sb.ToString(); return(command); }