concrete Representation the Entity Type
Inheritance: System.Data.Metadata.Edm.EntityTypeBase
        public EFTableProvider(EFDataModelProvider dataModel, EntitySet entitySet, EntityType entityType,
            Type entityClrType, Type parentEntityClrType, Type rootEntityClrType, string name)
            : base(dataModel) {

            EntityType = entityClrType;
            Name = name;
            DataContextPropertyName = entitySet.Name;
            ParentEntityType = parentEntityClrType;
            RootEntityType = rootEntityClrType;

            var genericMethod = DataModel.ContextType.GetMethod("CreateQuery");
            CreateQueryMethod = genericMethod.MakeGenericMethod(EntityType);
            CreateQueryString = CreateEntitySqlQueryString(entitySet);

            var keyMembers = entityType.KeyMembers;

            // columns (entity properties)
            // note 1: keys are also available through es.ElementType.KeyMembers
            // note 2: this includes "nav properties", kind of fancy, two-way relationship objects
            var columns = new List<ColumnProvider>();
            foreach (EdmMember m in entityType.Members) {
                if (EFColumnProvider.IsSupportedEdmMemberType(m) && IsPublicProperty(entityClrType, m.Name)) {
                    EFColumnProvider entityMember = new EFColumnProvider(entityType, this, m, keyMembers.Contains(m));
                    columns.Add(entityMember);
                }
            }

            _roColumns = new ReadOnlyCollection<ColumnProvider>(columns);
        }
        public EFColumnProvider(EntityType entityType, EFTableProvider table, EdmMember m, bool isPrimaryKey)
            : base(table) {
            EdmMember = m;
            IsPrimaryKey = isPrimaryKey;
            _table = table;
            MaxLength = 0;
            Name = EdmMember.Name;
            // 
            IsCustomProperty = false;

            // 
            var property = EdmMember as EdmProperty;

            if (property != null) {
                IsForeignKeyComponent = DetermineIsForeignKeyComponent(property);
                IsGenerated = IsServerGenerated(property);
            }

            ProcessFacets();

            var navProp = m as NavigationProperty;
            if (navProp != null) {
                _isAssociation = true;
                long key = EFAssociationProvider.BuildRelationshipKey(entityType, navProp.FromEndMember);
                ((EFDataModelProvider)table.DataModel).RelationshipEndLookup[key] = this;
            }
        }
        public EdmColumnProvider(EntityType entityType, EdmTableProvider table, EdmMember m, bool isPrimaryKey, bool supportPagingAndSorting)
            : base(table)
        {
            EdmMember = m;
            IsPrimaryKey = isPrimaryKey;
            _table = table;
            _supportSorting = supportPagingAndSorting;
            MaxLength = 0;
            Name = EdmMember.Name;
            // REVIEW Seems like extra properties added in partial classes are not even detected by the metadata engine
            IsCustomProperty = false;

            // REVIEW: This should probably be a debug assert or we should only pass an EmdProperty
            var property = EdmMember as EdmProperty;

            if (property != null) {
                IsForeignKeyComponent = DetermineIsForeignKeyComponent(property);
                IsGenerated = IsServerGenerated(property);
            }

            ProcessFacets();

            var navProp = m as NavigationProperty;
            if (navProp != null) {
                _isAssociation = true;
                long key = EdmAssociationProvider.BuildRelationshipKey(entityType, navProp.FromEndMember);
                ((EdmDataModelProvider)table.DataModel).RelationshipEndLookup[key] = this;
            }
        }
Esempio n. 4
0
 public static bool TryGetEntityType(ObjectContext context, Type clrType, out EntityType entityType)
 {
     entityType = null;
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     if (clrType == null)
     {
         throw new ArgumentNullException("clrType");
     }
     EdmType type = null;
     bool flag = context.MetadataWorkspace.TryGetType(clrType.Name, clrType.Namespace, DataSpace.OSpace, out type);
     if (!flag)
     {
         LoadAssemblyIntoWorkspace(context.MetadataWorkspace, clrType.Assembly);
         flag = context.MetadataWorkspace.TryGetType(clrType.Name, clrType.Namespace, DataSpace.OSpace, out type);
     }
     if (flag)
     {
         entityType = (EntityType)context.MetadataWorkspace.GetEdmSpaceType((StructuralType)type);
         return true;
     }
     return false;
 }
Esempio n. 5
0
        /// <summary>
        /// Create a column map for a ref type
        /// </summary>
        /// <param name="typeInfo">Type information for the ref type</param>
        /// <param name="name">Name of the column</param>
        /// <returns>Column map for the ref type</returns>
        private RefColumnMap CreateRefColumnMap(TypeInfo typeInfo, string name)
        {
            SimpleColumnMap entitySetIdColumnMap = null;

            if (typeInfo.HasEntitySetIdProperty)
            {
                entitySetIdColumnMap = CreateSimpleColumnMap(md.Helper.GetModelTypeUsage(typeInfo.EntitySetIdProperty), c_EntitySetIdColumnName);
            }

            // get the target entity type,
            md.EntityType entityType = (md.EntityType)(TypeHelpers.GetEdmType <md.RefType>(typeInfo.Type).ElementType);

            // Iterate through the list of "key" properties
            SimpleColumnMap[] keyColList = new SimpleColumnMap[entityType.KeyMembers.Count];
            for (int i = 0; i < keyColList.Length; ++i)
            {
                md.EdmMember property = entityType.KeyMembers[i];
                keyColList[i] = CreateSimpleColumnMap(md.Helper.GetModelTypeUsage(property), property.Name);
            }

            // Create the entity identity
            EntityIdentity identity = CreateEntityIdentity(entityType, entitySetIdColumnMap, keyColList);

            RefColumnMap result = new RefColumnMap(typeInfo.Type, name, identity);

            return(result);
        }
Esempio n. 6
0
        /// <summary>
        /// Add a new entry to the entityTypeToSet map
        /// </summary>
        /// <param name="entityType">entity type</param>
        /// <param name="entitySet">entityset producing this type</param>
        private void AddEntityTypeToSetEntry(md.EntityType entityType, md.EntitySet entitySet)
        {
            md.EntitySet      other;
            md.EntityTypeBase rootType = GetRootType(entityType);
            bool hasSingleEntitySet    = true;

            if (entitySet == null)
            {
                hasSingleEntitySet = false;
            }
            else if (m_entityTypeToEntitySetMap.TryGetValue(rootType, out other))
            {
                if (other != entitySet)
                {
                    hasSingleEntitySet = false;
                }
            }

            if (hasSingleEntitySet)
            {
                m_entityTypeToEntitySetMap[rootType] = entitySet;
            }
            else
            {
                m_entityTypeToEntitySetMap[rootType] = null;
            }
        }
        public EdmTableProvider(EdmDataModelProvider dataModel, EntitySet entitySet, EntityType entityType, string name,
            bool isReadonly, bool supportPagingAndSorting)
            : base(dataModel)
        {
            _isReadonly = isReadonly;
            SupportPaging = supportPagingAndSorting;
            Name = name;
            DataContextPropertyName = entitySet.Name;
            EdmEntityType = entityType;

            var keyMembers = entityType.KeyMembers;

            // columns (entity properties)
            // note 1: keys are also available through es.ElementType.KeyMembers
            // note 2: this includes "nav properties", kind of fancy, two-way relationship objects
            var columns = new List<ColumnProvider>();
            foreach (EdmMember m in entityType.Members) {
                if (EdmColumnProvider.IsSupportedEdmMemberType(m)) {
                    var entityMember = new EdmColumnProvider(entityType, this, m, keyMembers.Contains(m), supportPagingAndSorting);
                    columns.Add(entityMember);
                }
            }

            _roColumns = new ReadOnlyCollection<ColumnProvider>(columns);
        }
Esempio n. 8
0
 /// <summary>
 /// The constructor for constructing a RefType object with the entity type it references
 /// </summary>
 /// <param name="entityType">The entity type that this ref type references</param>
 /// <exception cref="System.ArgumentNullException">Thrown if entityType argument is null</exception>
 internal RefType(EntityType entityType)
     : base(GetIdentity(EntityUtil.GenericCheckArgumentNull(entityType, "entityType")), 
     EdmConstants.TransientNamespace, entityType.DataSpace)
 {
     _elementType = entityType;
     SetReadOnly();
 }
Esempio n. 9
0
        private INodeFactory CreateNodeFactoryForEntity(EntityType entity)
        {
            var type = MetadataHelpers.FindQualifiedTypeForEntity(entity);

            var factory = CreateClosedGenericNodeFactory(type);
            return factory;
        }
        public string GetGenerationOption(EdmProperty property, EntityType entity)
        {
            string result = "";
            bool isPk = entity.KeyMembers.Contains(property);
            MetadataProperty storeGeneratedPatternProperty = null;
            string storeGeneratedPatternPropertyValue = "None";

            if (property.MetadataProperties.TryGetValue(MetadataConstants.EDM_ANNOTATION_09_02 + ":StoreGeneratedPattern", false, out storeGeneratedPatternProperty))
                storeGeneratedPatternPropertyValue = storeGeneratedPatternProperty.Value.ToString();

            PrimitiveType edmType = (PrimitiveType)property.TypeUsage.EdmType;
            if (edmType == null && property.TypeUsage.EdmType is EnumType)
            {
                EnumType enumType = property.TypeUsage.EdmType as EnumType;
                edmType = enumType.UnderlyingType;
            }
            if (storeGeneratedPatternPropertyValue == "Computed")
            {
                result = ".HasDatabaseGeneratedOption(new Nullable<DatabaseGeneratedOption>(DatabaseGeneratedOption.Computed))";
            }
            else if ((edmType.ClrEquivalentType == typeof(int)) || (edmType.ClrEquivalentType == typeof(short)) || (edmType.ClrEquivalentType == typeof(long)))
            {
                if (isPk && (storeGeneratedPatternPropertyValue != "Identity"))
                    result = ".HasDatabaseGeneratedOption(new Nullable<DatabaseGeneratedOption>(DatabaseGeneratedOption.None))";
                else if ((!isPk || (entity.KeyMembers.Count > 1)) && (storeGeneratedPatternPropertyValue == "Identity"))
                    result = ".HasDatabaseGeneratedOption(new Nullable<DatabaseGeneratedOption>(DatabaseGeneratedOption.Identity))";
            }
            return result;
        }
        /// <summary>
        /// Gets the list of "identity" properties for an entity. Gets the
        /// "entitysetid" property in addition to the "key" properties
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private static PropertyRefList GetIdentityProperties(md.EntityType type)
        {
            PropertyRefList desiredProperties = GetKeyProperties(type);

            desiredProperties.Add(EntitySetIdPropertyRef.Instance);
            return(desiredProperties);
        }
        internal SerializableImplementor(EntityType ospaceEntityType)
        {
            _baseClrType = ospaceEntityType.ClrType;
            _baseImplementsISerializable = _baseClrType.IsSerializable && typeof(ISerializable).IsAssignableFrom(_baseClrType);

            if (_baseImplementsISerializable)
            {
                // Determine if interface implementation can be overridden.
                // Fortunately, there's only one method to check.
                var mapping = _baseClrType.GetInterfaceMap(typeof(ISerializable));
                _getObjectDataMethod = mapping.TargetMethods[0];

                // Members that implement interfaces must be public, unless they are explicitly implemented, in which case they are private and sealed (at least for C#).
                var canOverrideMethod = (_getObjectDataMethod.IsVirtual && !_getObjectDataMethod.IsFinal) && _getObjectDataMethod.IsPublic;

                if (canOverrideMethod)
                {
                    // Determine if proxied type provides the special serialization constructor.
                    // In order for the proxy class to properly support ISerializable, this constructor must not be private.
                    _serializationConstructor =
                        _baseClrType.GetConstructor(
                            BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null,
                            new[] { typeof(SerializationInfo), typeof(StreamingContext) }, null);

                    _canOverride = _serializationConstructor != null
                                   &&
                                   (_serializationConstructor.IsPublic || _serializationConstructor.IsFamily
                                    || _serializationConstructor.IsFamilyOrAssembly);
                }

                Debug.Assert(
                    !(_canOverride && (_getObjectDataMethod == null || _serializationConstructor == null)),
                    "Both GetObjectData method and Serialization Constructor must be present when proxy overrides ISerializable implementation.");
            }
        }
 /// <summary>
 /// Returns the abstract option if the entity is Abstract, otherwise returns String.Empty
 /// </summary>
 public string AbstractOption(EntityType entity)
 {
     if (entity.Abstract)
     {
         return "abstract";
     }
     return String.Empty;
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="metadata"></param>
        /// <param name="memberInfo"></param>
        /// <param name="entityKey"></param>
        public EntityRecordInfo(EntityType metadata, IEnumerable<EdmMember> memberInfo, EntityKey entityKey, EntitySet entitySet)
            : base(TypeUsage.Create(metadata), memberInfo) {
            EntityUtil.CheckArgumentNull<EntityKey>(entityKey, "entityKey");
            EntityUtil.CheckArgumentNull(entitySet, "entitySet");

            _entityKey = entityKey;
            _entitySet = entitySet;
            ValidateEntityType(entitySet);
        }
        public EntityRecordInfo(EntityType metadata, IEnumerable<EdmMember> memberInfo, EntityKey entityKey, EntitySet entitySet)
            : base(TypeUsage.Create(metadata), memberInfo)
        {
            //Contract.Requires(entityKey != null);
            //Contract.Requires(entitySet != null);

            _entityKey = entityKey;
            ValidateEntityType(entitySet);
        }
        internal DataContractImplementor(EntityType ospaceEntityType)
        {
            _baseClrType = ospaceEntityType.ClrType;

            var attributes = (DataContractAttribute[])_baseClrType.GetCustomAttributes(typeof(DataContractAttribute), false);
            if (attributes.Length > 0)
            {
                _dataContract = attributes[0];
            }
        }
Esempio n. 17
0
        // effects: Determines all the keys (unique and primary for
        // entityType) for entityType and returns a key. "prefix" gives the
        // path of the extent or end of a relationship in a relationship set
        // -- prefix is prepended to the entity's key fields to get the full memberpath
        internal static List<ExtentKey> GetKeysForEntityType(MemberPath prefix, EntityType entityType)
        {
            // CHANGE_ADYA_MULTIPLE_KEYS: currently there is a single key only. Need to support
            // keys inside complex types + unique keys
            var key = GetPrimaryKeyForEntityType(prefix, entityType);

            var keys = new List<ExtentKey>();
            keys.Add(key);
            return keys;
        }
        private void CheckType(EntityType ospaceEntityType)
        {
            _scalarMembers = new HashSet<EdmMember>();
            _relationshipMembers = new HashSet<EdmMember>();

            foreach (var member in ospaceEntityType.Members)
            {
                var clrProperty = EntityUtil.GetTopProperty(ospaceEntityType.ClrType, 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;
            }
        }
 internal StorageEntityTypeModificationFunctionMapping(
     EntityType entityType,
     StorageModificationFunctionMapping deleteFunctionMapping,
     StorageModificationFunctionMapping insertFunctionMapping,
     StorageModificationFunctionMapping updateFunctionMapping)
 {
     this.EntityType = EntityUtil.CheckArgumentNull(entityType, "entityType");
     this.DeleteFunctionMapping = deleteFunctionMapping;
     this.InsertFunctionMapping = insertFunctionMapping;
     this.UpdateFunctionMapping = updateFunctionMapping;
 }
Esempio n. 20
0
        private static string GetAssemblyNameFromEntity(EntityType entity)
        {
            var name = entity.FullName;
            string assemblyName = null;

            if (!_assemblyNames.TryGetValue(name, out assemblyName))
            {
                assemblyName = LoadEntityTypeAssemblyName(entity);
                _assemblyNames[name] = assemblyName;
            }
            return assemblyName;
        }
Esempio n. 21
0
        // effects: Returns the key for entityType prefixed with prefix (for
        // its memberPath)
        internal static ExtentKey GetPrimaryKeyForEntityType(MemberPath prefix, EntityType entityType)
        {
            var keyFields = new List<MemberPath>();
            foreach (var keyMember in entityType.KeyMembers)
            {
                Debug.Assert(keyMember != null, "Bogus key member in metadata");
                keyFields.Add(new MemberPath(prefix, keyMember));
            }

            // Just have one key for now
            var key = new ExtentKey(keyFields);
            return key;
        }
        /// <summary>
        /// Gets the list of key properties for an entity
        /// </summary>
        /// <param name="entityType"></param>
        /// <returns></returns>
        private static PropertyRefList GetKeyProperties(md.EntityType entityType)
        {
            PropertyRefList desiredProperties = new PropertyRefList();

            foreach (md.EdmMember p in entityType.KeyMembers)
            {
                md.EdmProperty edmP = p as md.EdmProperty;
                PlanCompiler.Assert(edmP != null, "EntityType had non-EdmProperty key member?");
                SimplePropertyRef pRef = new SimplePropertyRef(edmP);
                desiredProperties.Add(pRef);
            }
            return(desiredProperties);
        }
 /// <summary>
 /// Returns the type id for the given entity type, or null if non exists.
 /// </summary>
 internal object GetTypeId(EntityType entityType)
 {
     object result = null;
     foreach (var discriminatorTypePair in this.TypeMap)
     {
         if (discriminatorTypePair.Value.EdmEquals(entityType))
         {
             result = discriminatorTypePair.Key;
             break;
         }
     }
     return result;
 }
        internal StorageEntityTypeModificationFunctionMapping(
            EntityType entityType,
            StorageModificationFunctionMapping deleteFunctionMapping,
            StorageModificationFunctionMapping insertFunctionMapping,
            StorageModificationFunctionMapping updateFunctionMapping)
        {
            //Contract.Requires(entityType != null);

            EntityType = entityType;
            DeleteFunctionMapping = deleteFunctionMapping;
            InsertFunctionMapping = insertFunctionMapping;
            UpdateFunctionMapping = updateFunctionMapping;
        }
        public IPOCOImplementor(EntityType ospaceEntityType)
        {
            var baseType = ospaceEntityType.ClrType;
            _referenceProperties = new List<KeyValuePair<NavigationProperty, PropertyInfo>>();
            _collectionProperties = new List<KeyValuePair<NavigationProperty, PropertyInfo>>();

            _implementIEntityWithChangeTracker = (null == baseType.GetInterface(typeof(IEntityWithChangeTracker).Name));
            _implementIEntityWithRelationships = (null == baseType.GetInterface(typeof(IEntityWithRelationships).Name));

            CheckType(ospaceEntityType);

            _ospaceEntityType = ospaceEntityType;
        }
Esempio n. 26
0
 internal WithRelationship(AssociationSet associationSet,
                           AssociationEndMember fromEnd,
                           EntityType fromEndEntityType,
                           AssociationEndMember toEnd,
                           EntityType toEndEntityType,
                           IEnumerable<MemberPath> toEndEntityKeyMemberPaths)
 {
     m_associationSet = associationSet;
     m_fromEnd = fromEnd;
     m_fromEndEntityType = fromEndEntityType;
     m_toEnd = toEnd;
     m_toEndEntityType = toEndEntityType;
     m_toEndEntitySet = MetadataHelper.GetEntitySetAtEnd(associationSet, toEnd);
     m_toEndEntityKeyMemberPaths = toEndEntityKeyMemberPaths;
 }
        /// <summary>
        /// GetEntityRefOp handling
        ///
        /// Ask for the "identity" properties from the input entity, and push that
        /// down to my child
        /// </summary>
        /// <param name="op"></param>
        /// <param name="n"></param>
        public override void Visit(GetEntityRefOp op, Node n)
        {
            ScalarOp childOp = n.Child0.Op as ScalarOp;

            PlanCompiler.Assert(childOp != null, "input to GetEntityRefOp is not a ScalarOp?");

            //
            md.EntityType entityType = TypeHelpers.GetEdmType <md.EntityType>(childOp.Type);

            PropertyRefList desiredProperties = GetIdentityProperties(entityType);

            AddPropertyRefs(n.Child0, desiredProperties);

            VisitNode(n.Child0);
        }
        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);
                }
            }
        }
        /// <summary>
        /// Gets collection of RelationshipEndMember as navigation targets along the navigation path from the EntityType object 
        /// </summary>
        /// <param name="entityType">The EntityType instance to start with</param>
        /// <param name="navigation">The navigation path</param>
        /// <returns>Collection of navigation targets</returns>
        public static IEnumerable<RelationshipEndMember> GetNavigationStack(EntityType entityType, IEnumerable<string> navigation)
        {
            var result = new List<RelationshipEndMember>();

            EntityType currEntityType = entityType;
            UriType uriType = UriType.URI2;
            foreach(var nav in navigation)
            {
                ODataUriItem curr = new ODataUriItem(currEntityType, uriType);
                var next = curr.GetItem(nav);
                RelationshipEndMember navRole = (RelationshipEndMember)next.Item;
                result.Add(navRole);
                currEntityType = navRole.GetEntityType();
            }

            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="metadata"></param>
        /// <param name="entityKey"></param>
        internal EntityRecordInfo(EntityType metadata, EntityKey entityKey, EntitySet entitySet)
            : base(TypeUsage.Create(metadata)) {
            EntityUtil.CheckArgumentNull<EntityKey>(entityKey, "entityKey");

            _entityKey = entityKey;
            _entitySet = entitySet;
#if DEBUG
            try
            {
                ValidateEntityType(entitySet);
            }
            catch
            {
                Debug.Assert(false, "should always be valid EntityType when internally constructed");
                throw;
            }
#endif
        }
        /// <summary>
        /// Set the column mappings for each defaultMemberName.
        /// </summary>
        private void SetStructuralTypeColumnsRename(
            EntityType entityType,
            Collection<FunctionImportReturnTypePropertyMapping> columnsRenameMapping,
            bool isTypeOf)
        {
            //Contract.Requires(entityType != null);
            //Contract.Requires(columnsRenameMapping != null);

            foreach (var mapping in columnsRenameMapping)
            {
                if (!ColumnRenameMapping.Keys.Contains(mapping.CMember))
                {
                    ColumnRenameMapping[mapping.CMember] = new FunctionImportReturnTypeStructuralTypeColumnRenameMapping(mapping.CMember);
                }
                ColumnRenameMapping[mapping.CMember].AddRename(
                    new FunctionImportReturnTypeStructuralTypeColumn(mapping.SColumn, entityType, isTypeOf, mapping.LineInfo));
            }
        }
        internal EntityRecordInfo(EntityType metadata, EntityKey entityKey, EntitySet entitySet)
            : base(TypeUsage.Create(metadata))
        {
            //Contract.Requires(entityKey != null);

            _entityKey = entityKey;
#if DEBUG
            try
            {
                ValidateEntityType(entitySet);
            }
            catch
            {
                Debug.Assert(false, "should always be valid EntityType when internally constructed");
                throw;
            }
#endif
        }
Esempio n. 33
0
        private static string LoadEntityTypeAssemblyName(EntityType entity)
        {
            var pi = typeof(EntityType).GetProperty("ClrType", BindingFlags.Instance | BindingFlags.NonPublic);
            if (null == pi)
            {
                throw new InvalidOperationException(
                    "the entity metadata does not support an internal ClrType property as expected");
            }

            var type = pi.GetValue(entity) as Type;
            if (null == type)
            {
                throw new InvalidOperationException("failed to obtain a valid entity type reference from the specified entity metadata");
            }

            var assemblyName = new AssemblyName(type.Assembly.FullName).Name;

            return assemblyName;
        }
        internal EntityDataSourceWrapperCollection(ObjectContext context, EntitySet entitySet, EntityType restrictedEntityType)
        {
            EntityDataSourceUtil.CheckArgumentNull(context, "context");
            EntityDataSourceUtil.CheckArgumentNull(entitySet, "entitySet");

            _context = context;
            _wrapperList = new List<EntityDataSourceWrapper>();

            // get handles on the relevant workspaces
            MetadataWorkspace csWorkspace = ((EntityConnection)context.Connection).GetMetadataWorkspace();
            MetadataWorkspace ocWorkspace = context.MetadataWorkspace;

            // if no restricted type is given, we assume the entity set element type is exposed
            EntityType entityType = restrictedEntityType ?? entitySet.ElementType;
            _clrEntityType = EntityDataSourceUtil.GetClrType(ocWorkspace, entityType);
            
            // if no restricted type is given and the set is polymorphic, make the collection readonly
            if (null == restrictedEntityType &&
                1 < EntityDataSourceUtil.GetTypeAndSubtypesOf(entityType, csWorkspace.GetItemCollection(DataSpace.CSpace), true).Count())
            {
                _isReadOnly = true;
            }

            // gather the properties
            ReadOnlyCollection<EntityDataSourceColumn> columns = EntityDataSourceUtil.GetNamedColumns(csWorkspace, ocWorkspace, entitySet, entityType);
            List<PropertyDescriptor> visiblePropertyDescriptors = new List<PropertyDescriptor>(columns.Count);
            List<EntityDataSourceWrapperPropertyDescriptor> propertyDescriptors = new List<EntityDataSourceWrapperPropertyDescriptor>(columns.Count);
            foreach (EntityDataSourceColumn column in columns)
            {
                var descriptor = new EntityDataSourceWrapperPropertyDescriptor(this, column);
                propertyDescriptors.Add(descriptor);

                // if the descriptor does not have a dependent, it is exposed to the user
                if (!descriptor.Column.IsHidden)
                {
                    visiblePropertyDescriptors.Add(descriptor);
                }
            }

            _visiblePropertyDescriptors = new PropertyDescriptorCollection(visiblePropertyDescriptors.ToArray(), true);
            AllPropertyDescriptors = propertyDescriptors.AsReadOnly();
        }
Esempio n. 35
0
 /// <summary>
 /// Build out an EntityIdentity structure - for use by EntityColumnMap and RefColumnMap
 /// </summary>
 /// <param name="entityType">the entity type in question</param>
 /// <param name="entitySetIdColumnMap">column map for the entitysetid column</param>
 /// <param name="keyColumnMaps">column maps for the keys</param>
 /// <returns></returns>
 private EntityIdentity CreateEntityIdentity(md.EntityType entityType,
                                             SimpleColumnMap entitySetIdColumnMap,
                                             SimpleColumnMap[] keyColumnMaps)
 {
     //
     // If we have an entitysetid (and therefore, a column map for the entitysetid),
     // then use a discriminated entity identity; otherwise, we use a simpleentityidentity
     // instead
     //
     if (entitySetIdColumnMap != null)
     {
         return(new DiscriminatedEntityIdentity(entitySetIdColumnMap, m_typeInfo.EntitySetIdToEntitySetMap, keyColumnMaps));
     }
     else
     {
         md.EntitySet entitySet = m_typeInfo.GetEntitySet(entityType);
         PlanCompiler.Assert(entitySet != null, "Expected non-null entityset when no entitysetid is required. Entity type = " + entityType);
         return(new SimpleEntityIdentity(entitySet, keyColumnMaps));
     }
 }
        protected virtual void Visit(EntityType entityType)
        {
            foreach (var kmember in entityType.KeyMembers)
            {
                Visit(kmember);
            }

            foreach (var member in entityType.GetDeclaredOnlyMembers<EdmMember>())
            {
                Visit(member);
            }

            foreach (var nproperty in entityType.NavigationProperties)
            {
                Visit(nproperty);
            }

            foreach (var property in entityType.Properties)
            {
                Visit(property);
            }
        }
Esempio n. 37
0
        /// <summary>
        /// SetModified for Update
        /// </summary>
        /// <param name="apiContext"></param>
        /// <param name="entity"></param>
        protected static void SetModified(Helpers.ApiContext apiContext, Entities.EntityObject entity)
        {
            Model.OrmsContext context = (Model.OrmsContext)apiContext.CurrentContext;
            System.Data.Objects.ObjectStateEntry ose = context.ObjectStateManager.GetObjectStateEntry(entity);

            System.Data.Metadata.Edm.ItemCollection colleciton = null;
            if (context.MetadataWorkspace.TryGetItemCollection(System.Data.Metadata.Edm.DataSpace.CSpace, out colleciton))
            {
                System.String  typeFullName = entity.GetType().ToString();
                Edm.EntityType entiyType    =
                    colleciton.GetItems <Edm.EntityType>()
                    .Where(e => e.FullName.Equals(typeFullName, System.StringComparison.InvariantCultureIgnoreCase))
                    .First();

                // SET all properties modified except those who are in ignore list
                foreach (Edm.EdmProperty property in entiyType.Properties)
                {
                    if (!IsInIgnoreList(property.Name))
                    {
                        ose.SetModifiedProperty(property.Name);
                    }
                }
            }
        }
Esempio n. 38
0
        /// <summary>
        /// Add a new entry to the map. If an entry already exists, then this function
        /// simply returns the existing entry. Otherwise a new entry is created. If
        /// the type has a supertype, then we ensure that the supertype also exists in
        /// the map, and we add our info to the supertype's list of subtypes
        /// </summary>
        /// <param name="type">New type to add</param>
        /// <param name="discriminatorMap">type discriminator map</param>
        /// <returns>The TypeInfo for this type</returns>
        private TypeInfo CreateTypeInfoForStructuredType(md.TypeUsage type, ExplicitDiscriminatorMap discriminatorMap)
        {
            TypeInfo typeInfo;

            PlanCompiler.Assert(TypeUtils.IsStructuredType(type), "expected structured type. Found " + type);

            // Return existing entry, if one is available
            typeInfo = GetTypeInfo(type);
            if (typeInfo != null)
            {
                return(typeInfo);
            }

            // Ensure that my supertype has been added to the map.
            TypeInfo superTypeInfo = null;

            md.RefType refType;
            if (type.EdmType.BaseType != null)
            {
                superTypeInfo = CreateTypeInfoForStructuredType(md.TypeUsage.Create(type.EdmType.BaseType), discriminatorMap);
            }
            //
            // Handle Ref types also in a similar fashion
            //
            else if (TypeHelpers.TryGetEdmType <md.RefType>(type, out refType))
            {
                md.EntityType entityType = refType.ElementType as md.EntityType;
                if (entityType != null && entityType.BaseType != null)
                {
                    md.TypeUsage baseRefType = TypeHelpers.CreateReferenceTypeUsage(entityType.BaseType as md.EntityType);
                    superTypeInfo = CreateTypeInfoForStructuredType(baseRefType, discriminatorMap);
                }
            }

            //
            // Add the types of my properties to the TypeInfo map
            //
            foreach (md.EdmMember m in TypeHelpers.GetDeclaredStructuralMembers(type))
            {
                CreateTypeInfoForType(m.TypeUsage);
            }

            //
            // Get the types of the rel properties also
            //
            {
                md.EntityTypeBase entityType;
                if (TypeHelpers.TryGetEdmType <md.EntityTypeBase>(type, out entityType))
                {
                    foreach (RelProperty p in m_relPropertyHelper.GetDeclaredOnlyRelProperties(entityType))
                    {
                        CreateTypeInfoForType(p.ToEnd.TypeUsage);
                    }
                }
            }


            // Now add myself to the map
            typeInfo = TypeInfo.Create(type, superTypeInfo, discriminatorMap);
            m_typeInfoMap.Add(type, typeInfo);

            return(typeInfo);
        }