/// <summary> /// Gets all members of the ObjectSet that are currently in memory. /// </summary> /// <returns>All tracked members of the ObjectSet</returns> public static IEnumerable <TElement> GetTrackedEntities <TElement>(this ObjectSet <TElement> objectSet) where TElement : class { Validation.CheckArgumentNotNull(objectSet, "objectSet"); return(GetTrackedEntities(objectSet, ~EntityState.Detached)); }
public static T Field <T>(this IDataRecord record, string name) { Validation.CheckArgumentNotNull(record, "record"); Validation.CheckArgumentNotNull(name, "name"); return(Field <T>(record, record.GetOrdinal(name).ToString())); }
public static TEntity FindOrAttach <TElement, TEntity>(this ObjectSet <TElement> objectSet, TEntity entity) where TEntity : class, TElement where TElement : class { Validation.CheckArgumentNotNull(objectSet, "objectSet"); if (null == entity) { return(null); } string qualifiedEntitySetName = objectSet.EntitySet.EntityContainer.Name + "." + objectSet.EntitySet.Name; EntityKey entityKey = objectSet.Context.CreateEntityKey(qualifiedEntitySetName, entity); ObjectStateEntry existingStateEntry; if (objectSet.Context.ObjectStateManager.TryGetObjectStateEntry(entityKey, out existingStateEntry) && null != existingStateEntry.Entity) // A proxy entry may exist for the entity instance { try { return((TEntity)existingStateEntry.Entity); } catch (InvalidCastException) { throw new InvalidOperationException(Messages.AttachedEntityHasWrongType); } } objectSet.Attach(entity); return(entity); }
public static DbCommand CreateStoreCommand(this ObjectContext context, string commandText, CommandType commandType, params object[] parameters) { Validation.CheckArgumentNotNull(context, "context"); EntityConnection entityConnection = (EntityConnection)context.Connection; DbConnection storeConnection = entityConnection.StoreConnection; DbCommand storeCommand = storeConnection.CreateCommand(); // setup command storeCommand.CommandText = commandText; storeCommand.CommandType = commandType; if (null != parameters) { storeCommand.Parameters.AddRange(parameters); } // pass through command timeout as appropriate if (context.CommandTimeout.HasValue) { storeCommand.CommandTimeout = context.CommandTimeout.Value; } return(storeCommand); }
public static IEnumerable <TEntity> Bind <TEntity>(this IEnumerable <TEntity> source, ObjectContext context) where TEntity : class { Validation.CheckArgumentNotNull(source, "source"); Validation.CheckArgumentNotNull(context, "context"); return(source.Bind(context.CreateObjectSet <TEntity>())); }
public static T Field <T>(this IDataRecord record, int ordinal) { Validation.CheckArgumentNotNull(record, "record"); object value = record.IsDBNull(ordinal) ? null : record.GetValue(ordinal); return((T)value); }
/// <summary> /// Gets all members of the ObjectSet that are currently in memory /// with the given state(s). /// </summary> /// <param name="objectSet">Object set.</param> /// <param name="state">Entity state flags.</param> /// <typeparam name="TElement">Element type of object set.</typeparam> /// <returns>Tracked members of the ObjectSet in the given state.</returns> public static IEnumerable <TElement> GetTrackedEntities <TElement>(this ObjectSet <TElement> objectSet, EntityState state) where TElement : class { Validation.CheckArgumentNotNull(objectSet, "objectSet"); return(objectSet.Context.ObjectStateManager.GetObjectStateEntries(state) .Where(entry => IsMemberOfObjectSet(objectSet, entry)).Select(e => e.Entity).Cast <TElement>()); }
/// <summary> /// Associates results in the given source with an entity set. This supports tracking /// results in the state manager. If an existing element with the same key exists, it /// is returned instead. /// </summary> /// <typeparam name="TEntity">Entity type.</typeparam> /// <typeparam name="TBase">Base type for entity set.</typeparam> /// <param name="source">Entities to bind.</param> /// <param name="objectSet">Entity set to which elements should be bound.</param> /// <returns>Bound entities.</returns> public static IEnumerable <TEntity> Bind <TEntity, TBase>(this IEnumerable <TEntity> source, ObjectSet <TBase> objectSet) where TEntity : class, TBase where TBase : class { Validation.CheckArgumentNotNull(source, "source"); Validation.CheckArgumentNotNull(objectSet, "objectSet"); return(source.Select(objectSet.FindOrAttach)); }
private InvocationExpander(ParameterExpression parameter, Expression expansion, InvocationExpander previous) { Validation.CheckArgumentNotNull(parameter, "parameter"); Validation.CheckArgumentNotNull(expansion, "expansion"); Validation.CheckArgumentNotNull(previous, "previous"); _parameter = parameter; _expansion = expansion; _previous = previous; }
internal static Expression <Func <IDataRecord, T> > Optimize(ReadOnlyCollection <string> fieldNames, Expression <Func <IDataRecord, T> > shaper) { Validation.CheckArgumentNotNull(fieldNames, "fieldNames"); Validation.CheckArgumentNotNull(shaper, "shaper"); OptimizingExpressionVisitor visitor = new OptimizingExpressionVisitor(fieldNames, shaper.Parameters.Single()); return((Expression <Func <IDataRecord, T> >)visitor.Visit(shaper)); }
private static ObjectQuery <T> ToObjectQuery <T>(this IQueryable <T> source, string argumentName) { Validation.CheckArgumentNotNull(source, "source"); ObjectQuery <T> result = source as ObjectQuery <T>; if (null == result) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Messages.OperationRequiresObjectQuery, argumentName)); } return(result); }
public static void SetKey <T>(this EntityReference <T> entityReference, params object[] keyValues) where T : class, IEntityWithRelationships { Validation.CheckArgumentNotNull(entityReference, "entityReference"); // if null keyValues given, clear the entity key if (null == keyValues) { entityReference.EntityKey = null; } IEnumerable <string> keyComponentNames; int expectedKeyComponentCount; string entitySetName; if (null == entityReference.EntityKey) { // if there is no existing key, retrieve metadata through reflection EntitySet targetEntitySet = entityReference.GetTargetEntitySet(); keyComponentNames = targetEntitySet.ElementType.KeyMembers.Select(m => m.Name); expectedKeyComponentCount = targetEntitySet.ElementType.KeyMembers.Count; entitySetName = targetEntitySet.EntityContainer.Name + "." + targetEntitySet.Name; } else { // if there is an existing key, just borrow its metadata EntityKey existingKey = entityReference.EntityKey; keyComponentNames = existingKey.EntityKeyValues.Select(v => v.Key); expectedKeyComponentCount = existingKey.EntityKeyValues.Length; entitySetName = existingKey.EntityContainerName + "." + existingKey.EntitySetName; } // check that the correct number of key values is given if (keyValues != null && expectedKeyComponentCount != keyValues.Length) { throw new ArgumentException(Messages.UnexpectedKeyCount, "keyValues"); } // check if there are any null key components (if so, the entire key is assumed // to be null) if (keyValues == null || keyValues.Any(v => null == v)) { entityReference.EntityKey = null; } else { // create a new entity key with the given key component names and key component values EntityKey entityKey = new EntityKey(entitySetName, keyComponentNames.Zip(keyValues, (name, value) => new EntityKeyMember(name, value))); entityReference.EntityKey = entityKey; } }
public static EntitySet GetTargetEntitySet(this RelatedEnd relatedEnd) { Validation.CheckArgumentNotNull(relatedEnd, "relatedEnd"); AssociationSet associationSet = (AssociationSet)relatedEnd.RelationshipSet; if (null == associationSet) { throw new InvalidOperationException(Messages.CannotDetermineMetadataForRelatedEnd); } return(associationSet.AssociationSetEnds[relatedEnd.TargetRoleName].EntitySet); }
public Expression OptimizeMethodCall(ReadOnlyCollection <string> fieldNames, ParameterExpression recordParameter, MethodCallExpression methodCall) { Validation.CheckArgumentNotNull(fieldNames, "fieldNames"); Validation.CheckArgumentNotNull(methodCall, "methodCall"); MethodPattern pattern = GetMethodPattern(methodCall); if (pattern == MethodPattern.Unsupported) { // Cannot optimize this method. return(methodCall); } // if the input record (arguments[0]) is not the record parameter, we cannot // leverage field names to optimize the shaper if (recordParameter != methodCall.Arguments[0]) { return(methodCall); } Expression ordinalExpression; if (!TryGetOrdinalExpression(fieldNames, methodCall, pattern, out ordinalExpression)) { return(methodCall); } Type returnType = methodCall.Method.GetGenericArguments().Single(); bool canAssignNull = returnType.IsClass || (returnType.IsGenericType && typeof(Nullable <>) == returnType.GetGenericTypeDefinition()); // argument[0].GetValue(ordinal) Expression result = Expression.Call(methodCall.Arguments[0], s_getValue, ordinalExpression); if (canAssignNull) { // (returnType)(argument[0].IsDBNull(ordinal) ? null : result) result = Expression.Condition( Expression.Call(methodCall.Arguments[0], s_isDBNull, ordinalExpression), Expression.Constant(null, typeof(object)), result); } // (returnType)result result = Expression.Convert(result, returnType); return(result); }
/// <summary> /// Materializes the results of the given command. /// </summary> /// <param name="command">Command to execute.</param> /// <param name="commandBehavior">Command behavior to use when executing the command.</param> /// <returns>Shaped results.</returns> public IEnumerable <T> Materialize(DbCommand command, CommandBehavior commandBehavior) { Validation.CheckArgumentNotNull(command, "command"); using (command.Connection.CreateConnectionScope()) { using (DbDataReader reader = command.ExecuteReader(commandBehavior)) { foreach (T element in Materialize(reader)) { yield return(element); } } } }
public MaterializerOptimizedMethodAttribute(Type optimizerType) { Validation.CheckArgumentNotNull(optimizerType, "optimizerType"); ConstructorInfo defaultConstructor = optimizerType.GetConstructor(Type.EmptyTypes); if (!typeof(IMaterializerMethodOptimizer).IsAssignableFrom(optimizerType) || null == defaultConstructor) { throw new ArgumentException( string.Format(CultureInfo.InvariantCulture, Messages.InvalidOptimizerType, typeof(IMaterializerMethodOptimizer)), "optimizerType"); } Optimizer = (IMaterializerMethodOptimizer)defaultConstructor.Invoke(null); }
/// <summary> /// Returns binding list for the given query instance. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <returns></returns> public static IBindingList ToBindingList <T>(this IQueryable <T> source) { Validation.CheckArgumentNotNull(source, "source"); IListSource listSource = source as IListSource; if (null == listSource) { throw new ArgumentException(Messages.UnableToGetBindingList, "source"); } IBindingList bindingList = listSource.GetList() as IBindingList; if (null == bindingList) { throw new ArgumentException(Messages.UnableToGetBindingList, "source"); } return(bindingList); }
/// <summary> /// Materializes rows in the given reader. /// </summary> /// <param name="reader">Results to materialize.</param> /// <returns>Shaped results.</returns> public IEnumerable <T> Materialize(DbDataReader reader) { Validation.CheckArgumentNotNull(reader, "reader"); bool first = true; while (reader.Read()) { if (first) { InitializeShaper(reader); first = false; } yield return(shaperDelegate(reader)); } }
public static object GetKey <T>(this EntityReference <T> entityReference) where T : class, IEntityWithRelationships { Validation.CheckArgumentNotNull(entityReference, "entityReference"); EntityKey entityKey = entityReference.EntityKey; if (null == entityKey) { if (entityReference.GetTargetEntitySet().ElementType.KeyMembers.Count != 1) { throw new InvalidOperationException(Messages.SimpleKeyOnly); } return(null); } var entityKeyValues = entityKey.EntityKeyValues; if (entityKeyValues.Length != 1) { throw new InvalidOperationException(Messages.SimpleKeyOnly); } return(entityKeyValues[0].Value); }
public static object GetKey <T>(this EntityReference <T> entityReference, int keyOrdinal) where T : class, IEntityWithRelationships { Validation.CheckArgumentNotNull(entityReference, "entityReference"); if (keyOrdinal < 0) { throw new ArgumentOutOfRangeException("keyOrdinal"); } EntityKey entityKey = entityReference.EntityKey; if (null == entityKey) { if (entityReference.GetTargetEntitySet().ElementType.KeyMembers.Count <= keyOrdinal) { throw new ArgumentOutOfRangeException("keyOrdinal"); } return(null); } if (entityKey.EntityKeyValues.Length <= keyOrdinal) { throw new ArgumentOutOfRangeException("keyOrdinal"); } return(entityKey.EntityKeyValues[keyOrdinal].Value); }
/// <summary> /// Returns a handle on an IDisposable that can be used to safely control the lifetime /// of an open connection. If the connection is closed, it will be opened immediately /// and closed when the result of this method (the scope) is disposed. If the connection is already /// open, it remains open. /// <code> /// // Example with CreateConnectionScope /// using (command.Connection.CreateConnectionScope()) /// { /// command.ExecuteNonQuery(); /// } /// /// // Example without /// bool connectionOpened = command.Connection.State == ConnectionState.Closed; /// if (connectionOpened) /// { /// command.Connection.Open(); /// } /// try /// { /// command.ExecuteNonQuery(); /// } /// finally /// { /// if (connectionOpened && command.Connection.State == ConnectionState.Open) /// { /// command.Connection.Close(); /// } /// } /// </code> /// </summary> /// <param name="connection">Connection to open.</param> /// <returns>Scope closing the connection on dispose.</returns> public static IDisposable CreateConnectionScope(this DbConnection connection) { Validation.CheckArgumentNotNull(connection, "connection"); return(new OpenConnectionLifetime(connection)); }
public static IQueryable <TElement> ExpandInvocations <TElement>(this IQueryable <TElement> query) { Validation.CheckArgumentNotNull(query, "query"); return(query.Provider.CreateQuery <TElement>(query.Expression.ExpandInvocations())); }