public string GenerateQuery(EntityParameterCollection parameters) { Debug.Assert(parameters != null, "parameters != null"); if (string.IsNullOrWhiteSpace(_orderByClause) && !_filters.Any()) { return _baseQuery; } var sqlStatement = new StringBuilder(_baseQuery); var whereClause = CreateWhereClause(parameters); if (whereClause.Length != 0) { sqlStatement .Append(Environment.NewLine) .Append("WHERE") .Append(Environment.NewLine) .Append(whereClause); } if (!string.IsNullOrEmpty(_orderByClause)) { sqlStatement.Append(Environment.NewLine); sqlStatement.Append(_orderByClause); } return sqlStatement.ToString(); }
/// <summary> /// Inserts an <see cref="T:System.Object" /> into the /// <see cref="T:System.Data.Entity.Core.EntityClient.EntityParameterCollection" /> /// at the specified index. /// </summary> /// <param name="index">The zero-based index at which value should be inserted.</param> /// <param name="value"> /// An <see cref="T:System.Object" /> to be inserted in the /// <see cref="T:System.Data.Entity.Core.EntityClient.EntityParameterCollection" /> /// . /// </param> public override void Insert(int index, object value) { this.OnChange(); Check.NotNull <object>(value, nameof(value)); EntityParameterCollection.ValidateType(value); this.Validate(-1, value); this.InnerList.Insert(index, (EntityParameter)value); }
public override int Add(object value) { this.OnChange(); Check.NotNull <object>(value, nameof(value)); EntityParameterCollection.ValidateType(value); this.Validate(-1, value); this.InnerList.Add((EntityParameter)value); return(this.Count - 1); }
private void Replace(int index, object newValue) { List <EntityParameter> innerList = this.InnerList; EntityParameterCollection.ValidateType(newValue); this.Validate(index, newValue); EntityParameter entityParameter = innerList[index]; innerList[index] = (EntityParameter)newValue; entityParameter.ResetParent(); }
internal EntityCommand( DbInterceptionContext interceptionContext, EntityCommand.EntityDataReaderFactory factory) { this._designTimeVisible = true; this._commandType = CommandType.Text; this._updatedRowSource = UpdateRowSource.Both; this._parameters = new EntityParameterCollection(); this._interceptionContext = interceptionContext; this._enableQueryPlanCaching = true; this._entityDataReaderFactory = factory ?? new EntityCommand.EntityDataReaderFactory(); }
// internal to allow unit testing internal StringBuilder CreateWhereClause(EntityParameterCollection parameters) { Debug.Assert(parameters != null, "parameters != null"); var whereClause = new StringBuilder(); foreach (var alias in _filterAliases) { var allows = new StringBuilder(); var excludes = new StringBuilder(); foreach (var entry in _filters) { if (entry.Effect == EntityStoreSchemaFilterEffect.Allow) { AppendFilterEntry(allows, alias, entry, parameters); } else { Debug.Assert(entry.Effect == EntityStoreSchemaFilterEffect.Exclude, "did you add new value?"); AppendFilterEntry(excludes, alias, entry, parameters); } } if (allows.Length != 0) { // AND appended if this is not the first condition whereClause .AppendIfNotEmpty(Environment.NewLine) .AppendIfNotEmpty("AND") .AppendIfNotEmpty(Environment.NewLine); whereClause .Append("(") .Append(allows) .Append(")"); } if (excludes.Length != 0) { // AND appended if this is not the first condition whereClause .AppendIfNotEmpty(Environment.NewLine) .AppendIfNotEmpty("AND") .AppendIfNotEmpty(Environment.NewLine); whereClause .Append("NOT (") .Append(excludes) .Append(")"); } } return whereClause; }
/// <summary> /// Adds an array of values to the end of the /// <see cref="T:System.Data.Entity.Core.EntityClient.EntityParameterCollection" /> /// . /// </summary> /// <param name="values"> /// The <see cref="T:System.Array" /> values to add. /// </param> public override void AddRange(Array values) { this.OnChange(); Check.NotNull <Array>(values, nameof(values)); foreach (object obj in values) { EntityParameterCollection.ValidateType(obj); } foreach (EntityParameter entityParameter in values) { this.Validate(-1, (object)entityParameter); this.InnerList.Add(entityParameter); } }
internal EntityCommand(EntityDataReaderFactory factory) { // Initalize the member field with proper default values _designTimeVisible = true; _commandType = CommandType.Text; _updatedRowSource = UpdateRowSource.Both; _parameters = new EntityParameterCollection(); // Future Enhancement: (See SQLPT #300004256) At some point it would be // really nice to read defaults from a global configuration, but we're not // doing that today. _enableQueryPlanCaching = true; _entityDataReaderFactory = factory ?? new EntityDataReaderFactory(); }
internal EntityCommand( EntityCommandDefinition commandDefinition, DbInterceptionContext context, EntityCommand.EntityDataReaderFactory factory = null) : this(context, factory) { this._commandDefinition = commandDefinition; this._parameters = new EntityParameterCollection(); foreach (EntityParameter parameter in commandDefinition.Parameters) { this._parameters.Add(parameter.Clone()); } this._parameters.ResetIsDirty(); this._isCommandDefinitionBased = true; }
/// <summary>Removes the specified parameter from the collection.</summary> /// <param name="value"> /// A <see cref="T:System.Object" /> object to remove from the collection. /// </param> public override void Remove(object value) { this.OnChange(); Check.NotNull <object>(value, nameof(value)); EntityParameterCollection.ValidateType(value); int index = this.IndexOf(value); if (-1 != index) { this.RemoveIndex(index); } else if (this != ((EntityParameter)value).CompareExchangeParent((object)null, (object)this)) { throw new ArgumentException(Strings.EntityParameterCollectionRemoveInvalidObject); } }
// <summary> // Internal constructor used by EntityCommandDefinition // </summary> // <param name="commandDefinition"> The prepared command definition that can be executed using this EntityCommand </param> internal EntityCommand(EntityCommandDefinition commandDefinition, DbInterceptionContext context, EntityDataReaderFactory factory = null) : this(context, factory) { // Assign other member fields from the parameters _commandDefinition = commandDefinition; _parameters = new EntityParameterCollection(); // Make copies of the parameters foreach (var parameter in commandDefinition.Parameters) { _parameters.Add(parameter.Clone()); } // Reset the dirty flag that was set to true when the parameters were added so that it won't say // it's dirty to start with _parameters.ResetIsDirty(); // Track the fact that this command was created from and represents an already prepared command definition _isCommandDefinitionBased = true; }
/// <summary> /// Gets the location of the specified <see cref="T:System.Object" /> in the collection. /// </summary> /// <returns> /// The zero-based location of the specified <see cref="T:System.Object" /> that is a /// <see cref="T:System.Data.Entity.Core.EntityClient.EntityParameter" /> /// in the collection. Returns -1 when the object does not exist in the /// <see cref="T:System.Data.Entity.Core.EntityClient.EntityParameterCollection" /> /// . /// </returns> /// <param name="value"> /// The <see cref="T:System.Object" /> to find. /// </param> public override int IndexOf(object value) { if (value != null) { EntityParameterCollection.ValidateType(value); List <EntityParameter> innerList = this.InnerList; if (innerList != null) { int count = innerList.Count; for (int index = 0; index < count; ++index) { if (value == innerList[index]) { return(index); } } } } return(-1); }
// internal to allow unit testing internal static StringBuilder AppendFilterEntry( StringBuilder segment, string alias, EntityStoreSchemaFilterEntry entry, EntityParameterCollection parameters) { Debug.Assert(segment != null, "segment != null"); Debug.Assert(alias != null, "alias != null"); Debug.Assert(entry != null, "entry != null"); Debug.Assert(parameters != null, "parameters != null"); var filterText = new StringBuilder(); AppendComparison(filterText, alias, "CatalogName", entry.Catalog, parameters); AppendComparison(filterText, alias, "SchemaName", entry.Schema, parameters); AppendComparison( filterText, alias, "Name", entry.Catalog == null && entry.Schema == null && entry.Name == null ? "%" : entry.Name, parameters); segment .AppendIfNotEmpty(" OR ") .Append("(") .Append(filterText) .Append(")"); return segment; }
// internal to allow unit testing internal static StringBuilder AppendComparison( StringBuilder filterFragment, string alias, string propertyName, string value, EntityParameterCollection parameters) { Debug.Assert(filterFragment != null, "filterFragment != null"); Debug.Assert(alias != null, "alias != null"); Debug.Assert(propertyName != null, "propertyName != null"); Debug.Assert(parameters != null, "parameters != null"); if (value != null) { var parameterName = "p" + parameters.Count.ToString(CultureInfo.InvariantCulture); AppendComparisonFragment(filterFragment, alias, propertyName, parameterName); parameters.Add( new EntityParameter { ParameterName = parameterName, Value = value }); } return filterFragment; }
/// <summary> /// Gets the location of the specified <see cref="T:System.Data.Entity.Core.EntityClient.EntityParameter" /> with the specified name. /// </summary> /// <returns> /// The zero-based location of the specified <see cref="T:System.Data.Entity.Core.EntityClient.EntityParameter" /> with the specified case-sensitive name. Returns -1 when the object does not exist in the /// <see cref="T:System.Data.Entity.Core.EntityClient.EntityParameterCollection" /> /// . /// </returns> /// <param name="parameterName"> /// The case-sensitive name of the <see cref="T:System.Data.Entity.Core.EntityClient.EntityParameter" /> to find. /// </param> public override int IndexOf(string parameterName) { return(EntityParameterCollection.IndexOf((IEnumerable)this.InnerList, parameterName)); }
public void Executes_in_a_transaction_using_ExecutionStrategy_clears_parameters_for_retry() { var dbCommandMock = new Mock<DbCommand>(); dbCommandMock.Protected().Setup<Task<DbDataReader>>( "ExecuteDbDataReaderAsync", ItExpr.IsAny<CommandBehavior>(), ItExpr.IsAny<CancellationToken>()) .Throws(new InvalidOperationException("Foo")); var parameter = new EntityParameter(); var entityParameterCollection = new EntityParameterCollection(); dbCommandMock.Protected().SetupGet<DbParameterCollection>("DbParameterCollection").Returns(() => entityParameterCollection); var objectContext = Mock.Get(CreateObjectContext(dbCommandMock.Object)); var executionStrategyMock = new Mock<IDbExecutionStrategy>(); executionStrategyMock.Setup(m => m.RetriesOnFailure).Returns(true); executionStrategyMock.Setup( m => m.ExecuteAsync(It.IsAny<Func<Task<ObjectResult<object>>>>(), It.IsAny<CancellationToken>())) .Returns<Func<Task<ObjectResult<object>>>, CancellationToken>( (f, c) => { var result = f().Result; return Task.FromResult(result); }); MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(key => (Func<IDbExecutionStrategy>)(() => executionStrategyMock.Object)); try { // To simulate the retry, we will execute the query twice. // and we validate that in both ocassions the same exception is received // if parameter were not cleared, the second call would fail with the // sql paramters contained in an another sql collection error. Assert.Equal( "Foo", Assert.Throws<InvalidOperationException>( () => ExceptionHelpers.UnwrapAggregateExceptions( () => objectContext.Object.ExecuteStoreQueryAsync<object>("Bar", parameter).GetAwaiter().GetResult())) .Message); Assert.Equal( "Foo", Assert.Throws<InvalidOperationException>( () => ExceptionHelpers.UnwrapAggregateExceptions( () => objectContext.Object.ExecuteStoreQueryAsync<object>("Bar", parameter).GetAwaiter().GetResult())) .Message); } finally { MutableResolver.ClearResolvers(); } }
public void Executes_in_a_transaction_using_ExecutionStrategy_clears_parameters_for_retry() { var dbCommandMock = new Mock<DbCommand>(); dbCommandMock.Setup(m => m.ExecuteNonQuery()).Throws(new InvalidOperationException("Foo")); var objectContextMock = Mock.Get(CreateObjectContext(dbCommandMock.Object)); var executionStrategyMock = new Mock<IDbExecutionStrategy>(); var parameter = new EntityParameter(); var entityParameterCollection = new EntityParameterCollection(); dbCommandMock.Protected().SetupGet<DbParameterCollection>("DbParameterCollection").Returns(() => entityParameterCollection); objectContextMock.Setup( m => m.ExecuteInTransaction(It.IsAny<Func<int>>(), It.IsAny<IDbExecutionStrategy>(), It.IsAny<bool>(), It.IsAny<bool>())) .Returns<Func<int>, IDbExecutionStrategy, bool, bool>( (f, t, s, r) => { var result = f(); return result; }); executionStrategyMock.Setup(m => m.Execute(It.IsAny<Func<int>>())) .Returns<Func<int>>( f => { var result = f(); return result; }); MutableResolver.AddResolver<Func<IDbExecutionStrategy>>( key => (Func<IDbExecutionStrategy>)(() => executionStrategyMock.Object)); try { // To simulate the retry, we will execute the query twice. // and we validate that in both ocassions the same exception is received // if parameter were not cleared, the second call would fail with the // sql paramters contained in an another sql collection error. Assert.Equal( "Foo", Assert.Throws<InvalidOperationException>( () => objectContextMock.Object.ExecuteStoreCommand("foo", parameter)).Message); Assert.Equal( "Foo", Assert.Throws<InvalidOperationException>( () => objectContextMock.Object.ExecuteStoreCommand("foo", parameter)).Message); } finally { MutableResolver.ClearResolvers(); } }