Ejemplo n.º 1
0
        private static EntityProxyTypeInfo BuildType(
            ModuleBuilder moduleBuilder,
            ClrEntityType ospaceEntityType,
            MetadataWorkspace workspace)
        {
            EntityProxyFactory.ProxyTypeBuilder proxyTypeBuilder = new EntityProxyFactory.ProxyTypeBuilder(ospaceEntityType);
            Type type = proxyTypeBuilder.CreateType(moduleBuilder);
            EntityProxyTypeInfo proxyTypeInfo;

            if (type != (Type)null)
            {
                Assembly assembly = type.Assembly();
                if (!EntityProxyFactory._proxyRuntimeAssemblies.Contains(assembly))
                {
                    EntityProxyFactory._proxyRuntimeAssemblies.Add(assembly);
                    EntityProxyFactory.AddAssemblyToResolveList(assembly);
                }
                proxyTypeInfo = new EntityProxyTypeInfo(type, ospaceEntityType, proxyTypeBuilder.CreateInitalizeCollectionMethod(type), proxyTypeBuilder.BaseGetters, proxyTypeBuilder.BaseSetters, workspace);
                foreach (EdmMember lazyLoadMember in proxyTypeBuilder.LazyLoadMembers)
                {
                    EntityProxyFactory.InterceptMember(lazyLoadMember, type, proxyTypeInfo);
                }
                EntityProxyFactory.SetResetFKSetterFlagDelegate(type, proxyTypeInfo);
                EntityProxyFactory.SetCompareByteArraysDelegate(type);
            }
            else
            {
                proxyTypeInfo = (EntityProxyTypeInfo)null;
            }
            return(proxyTypeInfo);
        }
 // See IPropertyAccessorStrategy
 public void SetNavigationPropertyValue(RelatedEnd relatedEnd, object value)
 {
     if (relatedEnd != null)
     {
         if (relatedEnd.TargetAccessor.ValueSetter == null)
         {
             var type         = GetDeclaringType(relatedEnd);
             var propertyInfo = type.GetTopProperty(relatedEnd.TargetAccessor.PropertyName);
             if (propertyInfo == null)
             {
                 throw new EntityException(
                           Strings.PocoEntityWrapper_UnableToSetFieldOrProperty(relatedEnd.TargetAccessor.PropertyName, type.FullName));
             }
             var factory = new EntityProxyFactory();
             relatedEnd.TargetAccessor.ValueSetter = factory.CreateBaseSetter(propertyInfo.DeclaringType, propertyInfo);
         }
         try
         {
             relatedEnd.TargetAccessor.ValueSetter(_entity, value);
         }
         catch (Exception ex)
         {
             throw new EntityException(
                       Strings.PocoEntityWrapper_UnableToSetFieldOrProperty(
                           relatedEnd.TargetAccessor.PropertyName, _entity.GetType().FullName), ex);
         }
     }
 }
Ejemplo n.º 3
0
        private static Func <object, IEntityWrapper> CreateWrapperDelegate(Type entityType)
        {
            // For entities that implement all our interfaces we create a special lightweight wrapper that is both
            // smaller and faster than the strategy-based wrapper.
            // Otherwise, the wrapper is provided with different delegates depending on which interfaces are implemented.
            var        isIEntityWithRelationships = typeof(IEntityWithRelationships).IsAssignableFrom(entityType);
            var        isIEntityWithChangeTracker = typeof(IEntityWithChangeTracker).IsAssignableFrom(entityType);
            var        isIEntityWithKey           = typeof(IEntityWithKey).IsAssignableFrom(entityType);
            var        isProxy = EntityProxyFactory.IsProxyType(entityType);
            MethodInfo createDelegate;

            if (isIEntityWithRelationships &&
                isIEntityWithChangeTracker &&
                isIEntityWithKey &&
                !isProxy)
            {
                createDelegate = typeof(EntityWrapperFactory).GetMethod(
                    "CreateWrapperDelegateTypedLightweight", BindingFlags.NonPublic | BindingFlags.Static);
            }
            else if (isIEntityWithRelationships)
            {
                // This type of strategy wrapper is used when the entity implements IEntityWithRelationships
                // In this case it is important that the entity itself is used to create the RelationshipManager
                createDelegate = typeof(EntityWrapperFactory).GetMethod(
                    "CreateWrapperDelegateTypedWithRelationships", BindingFlags.NonPublic | BindingFlags.Static);
            }
            else
            {
                createDelegate = typeof(EntityWrapperFactory).GetMethod(
                    "CreateWrapperDelegateTypedWithoutRelationships", BindingFlags.NonPublic | BindingFlags.Static);
            }
            createDelegate = createDelegate.MakeGenericMethod(entityType);
            return((Func <object, IEntityWrapper>)createDelegate.Invoke(null, new object[0]));
        }
Ejemplo n.º 4
0
        /// <summary>
        ///     Called to create a new wrapper outside of the normal materialization process.
        ///     This method is typically used when a new entity is created outside the context and then is
        ///     added or attached.  The materializer bypasses this method and calls wrapper constructors
        ///     directory for performance reasons.
        ///     This method does not check whether or not the wrapper already exists in the context.
        /// </summary>
        /// <param name="entity"> The entity for which a wrapper will be created </param>
        /// <param name="key"> The key associated with that entity, or null </param>
        /// <returns> The new wrapper instance </returns>
        internal static IEntityWrapper CreateNewWrapper(object entity, EntityKey key)
        {
            Debug.Assert(!(entity is IEntityWrapper), "Object is an IEntityWrapper instance instead of the raw entity.");
            if (entity == null)
            {
                return(NullEntityWrapper.NullWrapper);
            }
            // We used a cache of functions based on the actual type of entity that we need to wrap.
            // Creatung these functions is slow, but once they are created they are relatively fast.
            var wrappedEntity = _delegateCache.Evaluate(entity.GetType())(entity);

            wrappedEntity.RelationshipManager.SetWrappedOwner(wrappedEntity, entity);
            // We cast to object here to avoid calling the overridden != operator on EntityKey.
            // This creates a very small perf gain, which is none-the-less significant for lean no-tracking cases.
            if ((object)key != null &&
                (object)wrappedEntity.EntityKey == null)
            {
                wrappedEntity.EntityKey = key;
            }

            // If the entity is a proxy, set the wrapper to match
            EntityProxyTypeInfo proxyTypeInfo;

            if (EntityProxyFactory.TryGetProxyType(entity.GetType(), out proxyTypeInfo))
            {
                proxyTypeInfo.SetEntityWrapper(wrappedEntity);
            }

            return(wrappedEntity);
        }
        public object GetNavigationPropertyValue(RelatedEnd relatedEnd)
        {
            object obj = (object)null;

            if (relatedEnd != null)
            {
                if (relatedEnd.TargetAccessor.ValueGetter == null)
                {
                    Type         declaringType = PocoPropertyAccessorStrategy.GetDeclaringType(relatedEnd);
                    PropertyInfo topProperty   = declaringType.GetTopProperty(relatedEnd.TargetAccessor.PropertyName);
                    if (topProperty == (PropertyInfo)null)
                    {
                        throw new EntityException(Strings.PocoEntityWrapper_UnableToSetFieldOrProperty((object)relatedEnd.TargetAccessor.PropertyName, (object)declaringType.FullName));
                    }
                    EntityProxyFactory entityProxyFactory = new EntityProxyFactory();
                    relatedEnd.TargetAccessor.ValueGetter = entityProxyFactory.CreateBaseGetter(topProperty.DeclaringType, topProperty);
                }
                bool state = relatedEnd.DisableLazyLoading();
                try
                {
                    obj = relatedEnd.TargetAccessor.ValueGetter(this._entity);
                }
                catch (Exception ex)
                {
                    throw new EntityException(Strings.PocoEntityWrapper_UnableToSetFieldOrProperty((object)relatedEnd.TargetAccessor.PropertyName, (object)this._entity.GetType().FullName), ex);
                }
                finally
                {
                    relatedEnd.ResetLazyLoading(state);
                }
            }
            return(obj);
        }
 public void SetNavigationPropertyValue(RelatedEnd relatedEnd, object value)
 {
     if (relatedEnd == null)
     {
         return;
     }
     if (relatedEnd.TargetAccessor.ValueSetter == null)
     {
         Type         declaringType = PocoPropertyAccessorStrategy.GetDeclaringType(relatedEnd);
         PropertyInfo topProperty   = declaringType.GetTopProperty(relatedEnd.TargetAccessor.PropertyName);
         if (topProperty == (PropertyInfo)null)
         {
             throw new EntityException(Strings.PocoEntityWrapper_UnableToSetFieldOrProperty((object)relatedEnd.TargetAccessor.PropertyName, (object)declaringType.FullName));
         }
         EntityProxyFactory entityProxyFactory = new EntityProxyFactory();
         relatedEnd.TargetAccessor.ValueSetter = entityProxyFactory.CreateBaseSetter(topProperty.DeclaringType, topProperty);
     }
     try
     {
         relatedEnd.TargetAccessor.ValueSetter(this._entity, value);
     }
     catch (Exception ex)
     {
         throw new EntityException(Strings.PocoEntityWrapper_UnableToSetFieldOrProperty((object)relatedEnd.TargetAccessor.PropertyName, (object)this._entity.GetType().FullName), ex);
     }
 }
Ejemplo n.º 7
0
        // See IPropertyAccessorStrategy
        public object GetNavigationPropertyValue(RelatedEnd relatedEnd)
        {
            object navPropValue = null;

            if (relatedEnd != null)
            {
                if (relatedEnd.TargetAccessor.ValueGetter == null)
                {
                    var type         = GetDeclaringType(relatedEnd);
                    var propertyInfo = EntityUtil.GetTopProperty(ref type, relatedEnd.TargetAccessor.PropertyName);
                    if (propertyInfo == null)
                    {
                        throw new EntityException(
                                  Strings.PocoEntityWrapper_UnableToSetFieldOrProperty(relatedEnd.TargetAccessor.PropertyName, type.FullName));
                    }
                    var factory = new EntityProxyFactory();
                    relatedEnd.TargetAccessor.ValueGetter = factory.CreateBaseGetter(type, propertyInfo);
                }
                try
                {
                    navPropValue = relatedEnd.TargetAccessor.ValueGetter(_entity);
                }
                catch (Exception ex)
                {
                    throw new EntityException(
                              Strings.PocoEntityWrapper_UnableToSetFieldOrProperty(
                                  relatedEnd.TargetAccessor.PropertyName, _entity.GetType().FullName), ex);
                }
            }
            return(navPropValue);
        }
Ejemplo n.º 8
0
        private static void SetResetFKSetterFlagDelegate(
            Type proxyType,
            EntityProxyTypeInfo proxyTypeInfo)
        {
            FieldInfo field = proxyType.GetField("_resetFKSetterFlag", BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.NonPublic);

            EntityProxyFactory.AssignInterceptionDelegate((Delegate)EntityProxyFactory.GetResetFKSetterFlagDelegate(proxyTypeInfo.EntityWrapperDelegate), field);
        }
        private static Func <object, IEntityWrapper> CreateWrapperDelegate(
            Type entityType)
        {
            bool flag1 = typeof(IEntityWithRelationships).IsAssignableFrom(entityType);
            bool flag2 = typeof(IEntityWithChangeTracker).IsAssignableFrom(entityType);
            bool flag3 = typeof(IEntityWithKey).IsAssignableFrom(entityType);
            bool flag4 = EntityProxyFactory.IsProxyType(entityType);

            return((Func <object, IEntityWrapper>)(!flag1 || !flag2 || (!flag3 || flag4) ? (!flag1 ? EntityWrapperFactory.CreateWrapperDelegateTypedWithoutRelationshipsMethod : EntityWrapperFactory.CreateWrapperDelegateTypedWithRelationshipsMethod) : EntityWrapperFactory.CreateWrapperDelegateTypedLightweightMethod).MakeGenericMethod(entityType).Invoke((object)null, new object[0]));
        }
Ejemplo n.º 10
0
        internal static bool TryGetProxyWrapper(object instance, out IEntityWrapper wrapper)
        {
            wrapper = (IEntityWrapper)null;
            EntityProxyTypeInfo proxyTypeInfo;

            if (EntityProxyFactory.IsProxyType(instance.GetType()) && EntityProxyFactory.TryGetProxyType(instance.GetType(), out proxyTypeInfo))
            {
                wrapper = proxyTypeInfo.GetEntityWrapper(instance);
            }
            return(wrapper != null);
        }
Ejemplo n.º 11
0
        private void CheckType(EntityType ospaceEntityType)
        {
            _scalarMembers       = new HashSet <EdmMember>();
            _relationshipMembers = new HashSet <EdmMember>();

            foreach (var member in ospaceEntityType.Members)
            {
                var clrProperty = ospaceEntityType.ClrType.GetTopProperty(member.Name);
                if (clrProperty != null &&
                    EntityProxyFactory.CanProxySetter(clrProperty))
                {
                    if (member.BuiltInTypeKind
                        == BuiltInTypeKind.EdmProperty)
                    {
                        if (_implementIEntityWithChangeTracker)
                        {
                            _scalarMembers.Add(member);
                        }
                    }
                    else if (member.BuiltInTypeKind
                             == BuiltInTypeKind.NavigationProperty)
                    {
                        if (_implementIEntityWithRelationships)
                        {
                            var navProperty  = (NavigationProperty)member;
                            var multiplicity = navProperty.ToEndMember.RelationshipMultiplicity;

                            if (multiplicity == RelationshipMultiplicity.Many)
                            {
                                if (clrProperty.PropertyType.IsGenericType()
                                    &&
                                    clrProperty.PropertyType.GetGenericTypeDefinition() == typeof(ICollection <>))
                                {
                                    _relationshipMembers.Add(member);
                                }
                            }
                            else
                            {
                                _relationshipMembers.Add(member);
                            }
                        }
                    }
                }
            }

            if (ospaceEntityType.Members.Count
                != _scalarMembers.Count + _relationshipMembers.Count)
            {
                _scalarMembers.Clear();
                _relationshipMembers.Clear();
                _implementIEntityWithChangeTracker = false;
                _implementIEntityWithRelationships = false;
            }
        }
Ejemplo n.º 12
0
        internal static IEnumerable <AssociationType> TryGetAllAssociationTypesFromProxyInfo(
            IEntityWrapper wrappedEntity)
        {
            EntityProxyTypeInfo proxyTypeInfo;

            if (!EntityProxyFactory.TryGetProxyType(wrappedEntity.Entity.GetType(), out proxyTypeInfo))
            {
                return((IEnumerable <AssociationType>)null);
            }
            return(proxyTypeInfo.GetAllAssociationTypes());
        }
Ejemplo n.º 13
0
 private void CheckType(EntityType ospaceEntityType)
 {
     this._members = new HashSet <EdmMember>();
     foreach (EdmMember member in ospaceEntityType.Members)
     {
         PropertyInfo topProperty = ospaceEntityType.ClrType.GetTopProperty(member.Name);
         if (topProperty != (PropertyInfo)null && EntityProxyFactory.CanProxyGetter(topProperty) && LazyLoadBehavior.IsLazyLoadCandidate(ospaceEntityType, member))
         {
             this._members.Add(member);
         }
     }
 }
        internal virtual IEntityWrapper WrapEntityUsingStateManagerGettingEntry(
            object entity,
            ObjectStateManager stateManager,
            out EntityEntry existingEntry)
        {
            IEntityWrapper wrapper = (IEntityWrapper)null;

            existingEntry = (EntityEntry)null;
            if (entity == null)
            {
                return(NullEntityWrapper.NullWrapper);
            }
            if (stateManager != null)
            {
                existingEntry = stateManager.FindEntityEntry(entity);
                if (existingEntry != null)
                {
                    return(existingEntry.WrappedEntity);
                }
                if (stateManager.TransactionManager.TrackProcessedEntities && stateManager.TransactionManager.WrappedEntities.TryGetValue(entity, out wrapper))
                {
                    return(wrapper);
                }
            }
            IEntityWithRelationships withRelationships = entity as IEntityWithRelationships;

            if (withRelationships != null)
            {
                RelationshipManager relationshipManager = withRelationships.RelationshipManager;
                if (relationshipManager == null)
                {
                    throw new InvalidOperationException(Strings.RelationshipManager_UnexpectedNull);
                }
                IEntityWrapper wrappedOwner = relationshipManager.WrappedOwner;
                if (!object.ReferenceEquals(wrappedOwner.Entity, entity))
                {
                    throw new InvalidOperationException(Strings.RelationshipManager_InvalidRelationshipManagerOwner);
                }
                return(wrappedOwner);
            }
            EntityProxyFactory.TryGetProxyWrapper(entity, out wrapper);
            if (wrapper == null)
            {
                IEntityWithKey entityWithKey = entity as IEntityWithKey;
                wrapper = EntityWrapperFactory.CreateNewWrapper(entity, entityWithKey == null ? (EntityKey)null : entityWithKey.EntityKey);
            }
            if (stateManager != null && stateManager.TransactionManager.TrackProcessedEntities)
            {
                stateManager.TransactionManager.WrappedEntities.Add(entity, wrapper);
            }
            return(wrapper);
        }
Ejemplo n.º 15
0
        private static void InterceptMember(
            EdmMember member,
            Type proxyType,
            EntityProxyTypeInfo proxyTypeInfo)
        {
            PropertyInfo topProperty = proxyType.GetTopProperty(member.Name);
            FieldInfo    field       = proxyType.GetField(LazyLoadImplementor.GetInterceptorFieldName(member.Name), BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.NonPublic);

            EntityProxyFactory.AssignInterceptionDelegate(EntityProxyFactory.GetInterceptorDelegateMethod.MakeGenericMethod(proxyType, topProperty.PropertyType).Invoke((object)null, new object[2]
            {
                (object)member,
                (object)proxyTypeInfo.EntityWrapperDelegate
            }) as Delegate, field);
        }
 /// <summary>
 ///     Constructs a wrapper for the given entity.
 ///     Note: use EntityWrapperFactory instead of calling this constructor directly.
 /// </summary>
 /// <param name="entity"> The entity to wrap </param>
 internal LightweightEntityWrapper(TEntity entity)
     : base(entity, entity.RelationshipManager)
 {
     Debug.Assert(
         entity is IEntityWithChangeTracker,
         "LightweightEntityWrapper only works with entities that implement IEntityWithChangeTracker");
     Debug.Assert(
         entity is IEntityWithRelationships,
         "LightweightEntityWrapper only works with entities that implement IEntityWithRelationships");
     Debug.Assert(entity is IEntityWithKey, "LightweightEntityWrapper only works with entities that implement IEntityWithKey");
     Debug.Assert(
         !EntityProxyFactory.IsProxyType(entity.GetType()), "LightweightEntityWrapper only works with entities that are not proxies");
     _entity = entity;
 }
Ejemplo n.º 17
0
        internal static bool TryGetAssociationTypeFromProxyInfo(
            IEntityWrapper wrappedEntity,
            string relationshipName,
            out AssociationType associationType)
        {
            associationType = (AssociationType)null;
            EntityProxyTypeInfo proxyTypeInfo;

            if (EntityProxyFactory.TryGetProxyType(wrappedEntity.Entity.GetType(), out proxyTypeInfo) && proxyTypeInfo != null)
            {
                return(proxyTypeInfo.TryGetNavigationPropertyAssociationType(relationshipName, out associationType));
            }
            return(false);
        }
            public void TryGetAssociationTypeFromProxyInfo_can_get_association_using_full_name()
            {
                using (var context = new RelationshipsContext())
                {
                    var proxy = context.WithRelationships.Create();

                    var mockWrapper = new Mock <IEntityWrapper>();
                    mockWrapper.Setup(m => m.Entity).Returns(proxy);

                    AssociationType associationType;
                    Assert.True(EntityProxyFactory.TryGetAssociationTypeFromProxyInfo(
                                    mockWrapper.Object, "System.Data.Entity.Core.Objects.Internal.ProxyWithRelationships_ManyToOnes", out associationType));
                    Assert.Equal("System.Data.Entity.Core.Objects.Internal.ProxyWithRelationships_ManyToOnes", associationType.FullName);
                }
            }
Ejemplo n.º 19
0
        private static bool TrySetBasePropertyValue(
            Type proxyType,
            string propertyName,
            object entity,
            object value)
        {
            EntityProxyTypeInfo proxyTypeInfo;

            if (!EntityProxyFactory.TryGetProxyType(proxyType, out proxyTypeInfo) || !proxyTypeInfo.ContainsBaseSetter(propertyName))
            {
                return(false);
            }
            proxyTypeInfo.BaseSetter(entity, propertyName, value);
            return(true);
        }
Ejemplo n.º 20
0
 /// <summary>
 ///     Constructs a wrapper as part of the materialization process.  This constructor is only used
 ///     during materialization where it is known that the entity being wrapped is newly constructed.
 ///     This means that some checks are not performed that might be needed when thw wrapper is
 ///     created at other times, and information such as the identity type is passed in because
 ///     it is readily available in the materializer.
 /// </summary>
 /// <param name="entity"> The entity to wrap </param>
 /// <param name="key"> The key for the entity </param>
 /// <param name="entitySet"> The entity set, or null if none is known </param>
 /// <param name="context"> The context to which the entity should be attached </param>
 /// <param name="mergeOption"> NoTracking for non-tracked entities, AppendOnly otherwise </param>
 /// <param name="identityType"> The type of the entity ignoring any possible proxy type </param>
 internal LightweightEntityWrapper(
     TEntity entity, EntityKey key, EntitySet entitySet, ObjectContext context, MergeOption mergeOption, Type identityType, bool overridesEquals)
     : base(entity, entity.RelationshipManager, entitySet, context, mergeOption, identityType, overridesEquals)
 {
     Debug.Assert(
         entity is IEntityWithChangeTracker,
         "LightweightEntityWrapper only works with entities that implement IEntityWithChangeTracker");
     Debug.Assert(
         entity is IEntityWithRelationships,
         "LightweightEntityWrapper only works with entities that implement IEntityWithRelationships");
     Debug.Assert(entity is IEntityWithKey, "LightweightEntityWrapper only works with entities that implement IEntityWithKey");
     Debug.Assert(
         !EntityProxyFactory.IsProxyType(entity.GetType()), "LightweightEntityWrapper only works with entities that are not proxies");
     _entity           = entity;
     _entity.EntityKey = key;
 }
        private void CheckType(EntityType ospaceEntityType)
        {
            _members = new HashSet <EdmMember>();

            foreach (var member in ospaceEntityType.Members)
            {
                var clrProperty = EntityUtil.GetTopProperty(ospaceEntityType.ClrType, member.Name);
                if (clrProperty != null
                    &&
                    EntityProxyFactory.CanProxyGetter(clrProperty)
                    &&
                    LazyLoadBehavior.IsLazyLoadCandidate(ospaceEntityType, member))
                {
                    _members.Add(member);
                }
            }
        }
            public void TryGetAllAssociationTypesFromProxyInfo_returns_all_associations_with_no_duplicates()
            {
                using (var context = new RelationshipsContext())
                {
                    var proxy = context.WithRelationships.Create();

                    var mockWrapper = new Mock <IEntityWrapper>();
                    mockWrapper.Setup(m => m.Entity).Returns(proxy);

                    var associations = EntityProxyFactory.TryGetAllAssociationTypesFromProxyInfo(mockWrapper.Object).Select(a => a.Name);

                    Assert.Equal(3, associations.Count());
                    Assert.Contains("ProxyWithRelationships_OneToOne", associations);
                    Assert.Contains("ProxyOneToMany_WithRelationships", associations);
                    Assert.Contains("ProxyWithRelationships_ManyToOnes", associations);
                }
            }
Ejemplo n.º 23
0
 internal static void TryCreateProxyTypes(
     IEnumerable <EntityType> ospaceEntityTypes,
     MetadataWorkspace workspace)
 {
     EntityProxyFactory._typeMapLock.EnterUpgradeableReadLock();
     try
     {
         foreach (EntityType ospaceEntityType in ospaceEntityTypes)
         {
             EntityProxyFactory.TryCreateProxyType(ospaceEntityType, workspace);
         }
     }
     finally
     {
         EntityProxyFactory._typeMapLock.ExitUpgradeableReadLock();
     }
 }
Ejemplo n.º 24
0
        public virtual Action <object, object> CreateBaseSetter(
            Type declaringType,
            PropertyInfo propertyInfo)
        {
            Action <object, object> nonProxySetter = DelegateFactory.CreateNavigationPropertySetter(declaringType, propertyInfo);
            string propertyName = propertyInfo.Name;

            return((Action <object, object>)((entity, value) =>
            {
                Type type = entity.GetType();
                if (EntityProxyFactory.IsProxyType(type) && EntityProxyFactory.TrySetBasePropertyValue(type, propertyName, entity, value))
                {
                    return;
                }
                nonProxySetter(entity, value);
            }));
        }
Ejemplo n.º 25
0
        public virtual Func <object, object> CreateBaseGetter(
            Type declaringType,
            PropertyInfo propertyInfo)
        {
            ParameterExpression   parameterExpression;
            Func <object, object> nonProxyGetter = Expression.Lambda <Func <object, object> >((Expression)Expression.Property((Expression)Expression.Convert((Expression)parameterExpression, declaringType), propertyInfo), parameterExpression).Compile();
            string propertyName = propertyInfo.Name;

            return((Func <object, object>)(entity =>
            {
                Type type = entity.GetType();
                object obj;
                if (EntityProxyFactory.IsProxyType(type) && EntityProxyFactory.TryGetBasePropertyValue(type, propertyName, entity, out obj))
                {
                    return obj;
                }
                return nonProxyGetter(entity);
            }));
        }
Ejemplo n.º 26
0
            private static void EmitBaseGetter(
                TypeBuilder typeBuilder,
                PropertyBuilder propertyBuilder,
                PropertyInfo baseProperty)
            {
                if (!EntityProxyFactory.CanProxyGetter(baseProperty))
                {
                    return;
                }
                MethodInfo       meth             = baseProperty.Getter();
                MethodAttributes methodAttributes = meth.Attributes & MethodAttributes.MemberAccessMask;
                MethodBuilder    mdBuilder        = typeBuilder.DefineMethod("get_" + baseProperty.Name, methodAttributes | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.SpecialName, baseProperty.PropertyType, Type.EmptyTypes);
                ILGenerator      ilGenerator      = mdBuilder.GetILGenerator();

                ilGenerator.Emit(OpCodes.Ldarg_0);
                ilGenerator.Emit(OpCodes.Call, meth);
                ilGenerator.Emit(OpCodes.Ret);
                propertyBuilder.SetGetMethod(mdBuilder);
            }
 private void CheckType(EntityType ospaceEntityType)
 {
     this._scalarMembers       = new HashSet <EdmMember>();
     this._relationshipMembers = new HashSet <EdmMember>();
     foreach (EdmMember member in ospaceEntityType.Members)
     {
         PropertyInfo topProperty = ospaceEntityType.ClrType.GetTopProperty(member.Name);
         if (topProperty != (PropertyInfo)null && EntityProxyFactory.CanProxySetter(topProperty))
         {
             if (member.BuiltInTypeKind == BuiltInTypeKind.EdmProperty)
             {
                 if (this._implementIEntityWithChangeTracker)
                 {
                     this._scalarMembers.Add(member);
                 }
             }
             else if (member.BuiltInTypeKind == BuiltInTypeKind.NavigationProperty && this._implementIEntityWithRelationships)
             {
                 if (((NavigationProperty)member).ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)
                 {
                     if (topProperty.PropertyType.IsGenericType() && topProperty.PropertyType.GetGenericTypeDefinition() == typeof(ICollection <>))
                     {
                         this._relationshipMembers.Add(member);
                     }
                 }
                 else
                 {
                     this._relationshipMembers.Add(member);
                 }
             }
         }
     }
     if (ospaceEntityType.Members.Count == this._scalarMembers.Count + this._relationshipMembers.Count)
     {
         return;
     }
     this._scalarMembers.Clear();
     this._relationshipMembers.Clear();
     this._implementIEntityWithChangeTracker = false;
     this._implementIEntityWithRelationships = false;
 }
Ejemplo n.º 28
0
        internal static EntityProxyTypeInfo GetProxyType(
            ClrEntityType ospaceEntityType,
            MetadataWorkspace workspace)
        {
            EntityProxyTypeInfo proxyTypeInfo = (EntityProxyTypeInfo)null;

            if (EntityProxyFactory.TryGetProxyType(ospaceEntityType.ClrType, ospaceEntityType.CSpaceTypeName, out proxyTypeInfo))
            {
                proxyTypeInfo?.ValidateType(ospaceEntityType);
                return(proxyTypeInfo);
            }
            EntityProxyFactory._typeMapLock.EnterUpgradeableReadLock();
            try
            {
                return(EntityProxyFactory.TryCreateProxyType((EntityType)ospaceEntityType, workspace));
            }
            finally
            {
                EntityProxyFactory._typeMapLock.ExitUpgradeableReadLock();
            }
        }
        internal static IEntityWrapper CreateNewWrapper(object entity, EntityKey key)
        {
            if (entity == null)
            {
                return(NullEntityWrapper.NullWrapper);
            }
            IEntityWrapper entityWrapper = EntityWrapperFactory._delegateCache.Evaluate(entity.GetType())(entity);

            entityWrapper.RelationshipManager.SetWrappedOwner(entityWrapper, entity);
            if ((object)key != null && (object)entityWrapper.EntityKey == null)
            {
                entityWrapper.EntityKey = key;
            }
            EntityProxyTypeInfo proxyTypeInfo;

            if (EntityProxyFactory.TryGetProxyType(entity.GetType(), out proxyTypeInfo))
            {
                proxyTypeInfo.SetEntityWrapper(entityWrapper);
            }
            return(entityWrapper);
        }
Ejemplo n.º 30
0
        // Creates delegates that create strategy objects appropriate for the type of entity.
        private static void CreateStrategies <TEntity>(
            out Func <object, IPropertyAccessorStrategy> createPropertyAccessorStrategy,
            out Func <object, IChangeTrackingStrategy> createChangeTrackingStrategy,
            out Func <object, IEntityKeyStrategy> createKeyStrategy)
        {
            var entityType = typeof(TEntity);
            var isIEntityWithRelationships = typeof(IEntityWithRelationships).IsAssignableFrom(entityType);
            var isIEntityWithChangeTracker = typeof(IEntityWithChangeTracker).IsAssignableFrom(entityType);
            var isIEntityWithKey           = typeof(IEntityWithKey).IsAssignableFrom(entityType);
            var isProxy = EntityProxyFactory.IsProxyType(entityType);

            if (!isIEntityWithRelationships || isProxy)
            {
                createPropertyAccessorStrategy = GetPocoPropertyAccessorStrategyFunc();
            }
            else
            {
                createPropertyAccessorStrategy = GetNullPropertyAccessorStrategyFunc();
            }

            if (isIEntityWithChangeTracker)
            {
                createChangeTrackingStrategy = GetEntityWithChangeTrackerStrategyFunc();
            }
            else
            {
                createChangeTrackingStrategy = GetSnapshotChangeTrackingStrategyFunc();
            }

            if (isIEntityWithKey)
            {
                createKeyStrategy = GetEntityWithKeyStrategyStrategyFunc();
            }
            else
            {
                createKeyStrategy = GetPocoEntityKeyStrategyFunc();
            }
        }