internal StorageModificationFunctionMapping( EntitySetBase entitySet, EntityTypeBase entityType, EdmFunction function, IEnumerable<StorageModificationFunctionParameterBinding> parameterBindings, FunctionParameter rowsAffectedParameter, IEnumerable<StorageModificationFunctionResultBinding> resultBindings) { Contract.Requires(entitySet != null); Contract.Requires(function != null); Contract.Requires(parameterBindings != null); Function = function; RowsAffectedParameter = rowsAffectedParameter; ParameterBindings = parameterBindings.ToList().AsReadOnly(); if (null != resultBindings) { var bindings = resultBindings.ToList(); if (0 < bindings.Count) { ResultBindings = bindings.AsReadOnly(); } } CollocatedAssociationSetEnds = GetReferencedAssociationSetEnds(entitySet as EntitySet, entityType as EntityType, parameterBindings) .ToList() .AsReadOnly(); }
/// <summary> /// Merge the discriminatorMap info we just found with what we've already found. /// In practice, if either the current or the new map is from an OfTypeOnly view, we /// have to avoid the optimizations. /// If we have a new map that is a superset of the current map, then we can just swap /// the new map for the current one. /// If the current map is tha super set of the new one ther's nothing to do. /// (Of course, if neither has changed, then we really don't need to look) /// </summary> internal void Merge(EntityTypeBase neededRootEntityType, bool includesSubtypes, ExplicitDiscriminatorMap discriminatorMap) { // If what we've found doesn't exactly match what we are looking for we have more work to do if (RootEntityType != neededRootEntityType || IncludesSubTypes != includesSubtypes) { if (!IncludesSubTypes || !includesSubtypes) { // If either the original or the new map is from an of-type-only view we can't // merge, we just have to not optimize this case. DiscriminatorMap = null; } if (TypeSemantics.IsSubTypeOf(RootEntityType, neededRootEntityType)) { // we're asking for a super type of existing type, and what we had is a proper // subset of it -we can replace the existing item. RootEntityType = neededRootEntityType; DiscriminatorMap = discriminatorMap; } if (!TypeSemantics.IsSubTypeOf(neededRootEntityType, RootEntityType)) { // If either the original or the new map is from an of-type-only view we can't // merge, we just have to not optimize this case. DiscriminatorMap = null; } } }
/// <summary> /// Initializes a new ModificationFunctionMapping instance. /// </summary> /// <param name="entitySet">The entity or association set.</param> /// <param name="entityType">The entity or association type.</param> /// <param name="function">The metadata of function to which we should bind.</param> /// <param name="parameterBindings">Bindings for function parameters.</param> /// <param name="rowsAffectedParameter">The output parameter producing number of rows affected.</param> /// <param name="resultBindings">Bindings for the results of function evaluation</param> public ModificationFunctionMapping( EntitySetBase entitySet, EntityTypeBase entityType, EdmFunction function, IEnumerable<ModificationFunctionParameterBinding> parameterBindings, FunctionParameter rowsAffectedParameter, IEnumerable<ModificationFunctionResultBinding> resultBindings) { Check.NotNull(entitySet, "entitySet"); Check.NotNull(function, "function"); Check.NotNull(parameterBindings, "parameterBindings"); _function = function; _rowsAffectedParameter = rowsAffectedParameter; _parameterBindings = new ReadOnlyCollection<ModificationFunctionParameterBinding>(parameterBindings.ToList()); if (null != resultBindings) { var bindings = resultBindings.ToList(); if (0 < bindings.Count) { _resultBindings = new ReadOnlyCollection<ModificationFunctionResultBinding>(bindings); } } _collocatedAssociationSetEnds = new ReadOnlyCollection<AssociationSetEnd>( GetReferencedAssociationSetEnds(entitySet as EntitySet, entityType as EntityType, parameterBindings) .ToList()); }
internal StorageModificationFunctionMapping( EntitySetBase entitySet, EntityTypeBase entityType, EdmFunction function, IEnumerable<StorageModificationFunctionParameterBinding> parameterBindings, FunctionParameter rowsAffectedParameter, IEnumerable<StorageModificationFunctionResultBinding> resultBindings) { DebugCheck.NotNull(entitySet); DebugCheck.NotNull(function); DebugCheck.NotNull(parameterBindings); _function = function; _rowsAffectedParameter = rowsAffectedParameter; ParameterBindings = parameterBindings.ToList().AsReadOnly(); if (null != resultBindings) { var bindings = resultBindings.ToList(); if (0 < bindings.Count) { ResultBindings = bindings.AsReadOnly(); } } CollocatedAssociationSetEnds = GetReferencedAssociationSetEnds(entitySet as EntitySet, entityType as EntityType, parameterBindings) .ToList() .AsReadOnly(); }
/// <summary> /// Constructs the name of the collection type /// </summary> /// <param name="entityTypeBase"> The entity type base that this ref type refers to </param> /// <returns> The identity of the resulting ref type </returns> private static string GetIdentity(EntityTypeBase entityTypeBase) { var builder = new StringBuilder(50); builder.Append("reference["); entityTypeBase.BuildIdentity(builder); builder.Append("]"); return builder.ToString(); }
private static string GetIdentity(EntityTypeBase entityTypeBase) { StringBuilder builder = new StringBuilder(50); builder.Append("reference["); entityTypeBase.BuildIdentity(builder); builder.Append("]"); return(builder.ToString()); }
private static EdmProperty[] GetProperties( EntityTypeBase entityType, IList <PropertyRefElement> properties) { EdmProperty[] edmPropertyArray = new EdmProperty[properties.Count]; for (int index = 0; index < properties.Count; ++index) { edmPropertyArray[index] = (EdmProperty)entityType.Members[properties[index].Name]; } return(edmPropertyArray); }
// <summary> // Gets the "single" entityset that stores instances of this type // </summary> internal md.EntitySet GetEntitySet(md.EntityTypeBase type) { md.EntitySet set; var rootType = GetRootType(type); if (!m_entityTypeToEntitySetMap.TryGetValue(rootType, out set)) { return(null); } return(set); }
/// <summary> /// Returns mappings for the given set/type only if the mapping applies also to childEntittyType either via IsTypeOf or explicitly specifying multiple types in mapping fragments. /// </summary> private static IEnumerable<StorageTypeMapping> GetIsTypeOfMappingsForEntitySetAndType( StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase entityType, EntityTypeBase childEntityType) { foreach (var mapping in GetMappingsForEntitySetAndType(mappingCollection, container, entitySet, entityType)) { if (mapping.IsOfTypes.Any(parentType => parentType.IsAssignableFrom(childEntityType)) || mapping.Types.Contains(childEntityType)) { yield return mapping; } } }
// <summary> // Returns mappings for the given set/type only if the mapping applies also to childEntittyType either via IsTypeOf or explicitly specifying multiple types in mapping fragments. // </summary> private static IEnumerable <TypeMapping> GetIsTypeOfMappingsForEntitySetAndType( StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase entityType, EntityTypeBase childEntityType) { foreach (var mapping in GetMappingsForEntitySetAndType(mappingCollection, container, entitySet, entityType)) { if (mapping.IsOfTypes.Any(parentType => parentType.IsAssignableFrom(childEntityType)) || mapping.Types.Contains(childEntityType)) { yield return(mapping); } } }
// <summary> // Returns all mapping fragments for the given entity set's types and their parent types. // </summary> internal static IEnumerable <TypeMapping> GetMappingsForEntitySetAndSuperTypes( StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase childEntityType) { return(MetadataHelper.GetTypeAndParentTypesOf(childEntityType, true /*includeAbstractTypes*/).SelectMany( edmType => { var entityTypeBase = edmType as EntityTypeBase; return edmType.EdmEquals(childEntityType) ? GetMappingsForEntitySetAndType(mappingCollection, container, entitySet, entityTypeBase) : GetIsTypeOfMappingsForEntitySetAndType( mappingCollection, container, entitySet, entityTypeBase, childEntityType); }).ToList()); }
/// <summary> /// Returns all mapping fragments for the given entity set's types and their parent types. /// </summary> internal static IEnumerable<StorageTypeMapping> GetMappingsForEntitySetAndSuperTypes( StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase childEntityType) { return MetadataHelper.GetTypeAndParentTypesOf(childEntityType, true /*includeAbstractTypes*/).SelectMany( edmType => { var entityTypeBase = edmType as EntityTypeBase; return edmType.EdmEquals(childEntityType) ? GetMappingsForEntitySetAndType(mappingCollection, container, entitySet, entityTypeBase) : GetIsTypeOfMappingsForEntitySetAndType( mappingCollection, container, entitySet, entityTypeBase, childEntityType); }).ToList(); }
internal EntitySetBase( string name, string schema, string table, string definingQuery, EntityTypeBase entityType) { Check.NotNull <EntityTypeBase>(entityType, nameof(entityType)); Check.NotEmpty(name, nameof(name)); this._name = name; this._schema = schema; this._table = table; this._definingQuery = definingQuery; this.ElementType = entityType; }
private static IEnumerable <TypeMapping> GetIsTypeOfMappingsForEntitySetAndType( StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase entityType, EntityTypeBase childEntityType) { foreach (TypeMapping typeMapping in MappingMetadataHelper.GetMappingsForEntitySetAndType(mappingCollection, container, entitySet, entityType)) { if (typeMapping.IsOfTypes.Any <EntityTypeBase>((Func <EntityTypeBase, bool>)(parentType => parentType.IsAssignableFrom((EdmType)childEntityType))) || typeMapping.Types.Contains(childEntityType)) { yield return(typeMapping); } } }
internal static IEnumerable <TypeMapping> GetMappingsForEntitySetAndSuperTypes( StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase childEntityType) { return((IEnumerable <TypeMapping>)MetadataHelper.GetTypeAndParentTypesOf((EdmType)childEntityType, true).SelectMany <EdmType, TypeMapping>((Func <EdmType, IEnumerable <TypeMapping> >)(edmType => { EntityTypeBase entityType = edmType as EntityTypeBase; if (!edmType.EdmEquals((MetadataItem)childEntityType)) { return MappingMetadataHelper.GetIsTypeOfMappingsForEntitySetAndType(mappingCollection, container, entitySet, entityType, childEntityType); } return MappingMetadataHelper.GetMappingsForEntitySetAndType(mappingCollection, container, entitySet, entityType); })).ToList <TypeMapping>()); }
internal static IEnumerable <TypeMapping> GetMappingsForEntitySetAndType( StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase entityType) { EntityContainerMapping containerMapping = MappingMetadataHelper.GetEntityContainerMap(mappingCollection, container); EntitySetBaseMapping extentMap = containerMapping.GetSetMapping(entitySet.Name); if (extentMap != null) { foreach (TypeMapping typeMapping in extentMap.TypeMappings.Where <TypeMapping>((Func <TypeMapping, bool>)(map => map.Types.Union <EntityTypeBase>((IEnumerable <EntityTypeBase>)map.IsOfTypes).Contains <EntityTypeBase>(entityType)))) { yield return(typeMapping); } } }
internal EntityType( string name, string namespaceName, DataSpace dataSpace, IEnumerable <string> keyMemberNames, IEnumerable <EdmMember> members) : base(name, namespaceName, dataSpace) { if (members != null) { EntityTypeBase.CheckAndAddMembers(members, this); } if (keyMemberNames == null) { return; } this.CheckAndAddKeyMembers(keyMemberNames); }
internal static IEnumerable <EntityTypeModificationFunctionMapping> GetModificationFunctionMappingsForEntitySetAndType( StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase entityType) { EntityContainerMapping containerMapping = MappingMetadataHelper.GetEntityContainerMap(mappingCollection, container); EntitySetBaseMapping extentMap = containerMapping.GetSetMapping(entitySet.Name); EntitySetMapping entitySetMapping = extentMap as EntitySetMapping; if (entitySetMapping != null && entitySetMapping != null) { foreach (EntityTypeModificationFunctionMapping modificationFunctionMapping in entitySetMapping.ModificationFunctionMappings.Where <EntityTypeModificationFunctionMapping>((Func <EntityTypeModificationFunctionMapping, bool>)(functionMap => functionMap.EntityType.Equals((object)entityType)))) { yield return(modificationFunctionMapping); } } }
internal static IEnumerable<StorageTypeMapping> GetMappingsForEntitySetAndType( StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase entityType) { DebugCheck.NotNull(entityType); var containerMapping = GetEntityContainerMap(mappingCollection, container); var extentMap = containerMapping.GetSetMapping(entitySet.Name); //The Set may have no mapping if (extentMap != null) { //for each mapping fragment of Type we are interested in within the given set //Check use of IsOfTypes in Code review foreach (var typeMap in extentMap.TypeMappings.Where(map => map.Types.Union(map.IsOfTypes).Contains(entityType))) { yield return typeMap; } } }
// <summary> // The constructor for constructing the EntitySet with a given name and an entity type // </summary> // <param name="name"> The name of the EntitySet </param> // <param name="schema"> The db schema </param> // <param name="table"> The db table </param> // <param name="definingQuery"> The provider specific query that should be used to retrieve the EntitySet </param> // <param name="entityType"> The entity type of the entities that this entity set type contains </param> // <exception cref="System.ArgumentNullException">Thrown if the name or entityType argument is null</exception> internal EntitySetBase(string name, string schema, string table, string definingQuery, EntityTypeBase entityType) { Check.NotNull(entityType, "entityType"); Check.NotEmpty(name, "name"); // catalogName, schemaName & tableName are allowed to be null, empty & non-empty _name = name; //---- name of the 'schema' //---- this is used by the SQL Gen utility to support generation of the correct name in the store _schema = schema; //---- name of the 'table' //---- this is used by the SQL Gen utility to support generation of the correct name in the store _table = table; //---- the Provider specific query to use to retrieve the EntitySet data _definingQuery = definingQuery; ElementType = entityType; }
internal static IEnumerable<StorageEntityTypeModificationFunctionMapping> GetModificationFunctionMappingsForEntitySetAndType( StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase entityType) { var containerMapping = GetEntityContainerMap(mappingCollection, container); var extentMap = containerMapping.GetSetMapping(entitySet.Name); var entitySetMapping = extentMap as StorageEntitySetMapping; //The Set may have no mapping if (entitySetMapping != null) { if (entitySetMapping != null) //could be association set mapping { foreach ( var v in entitySetMapping.ModificationFunctionMappings.Where(functionMap => functionMap.EntityType.Equals(entityType))) { yield return v; } } } }
internal IEnumerable <PropertyRef> GetKeyPropertyRefs() { md.EntityTypeBase entityType = null; md.RefType refType = null; if (TypeHelpers.TryGetEdmType(m_type, out refType)) { entityType = refType.ElementType; } else { entityType = TypeHelpers.GetEdmType <md.EntityTypeBase>(m_type); } // Walk through the list of keys of the entity type, and find their analogs in the // "flattened" type foreach (var p in entityType.KeyMembers) { // Eventually this could be RelationshipEndMember, but currently only properties are suppported as key members PlanCompiler.Assert(p is md.EdmProperty, "Non-EdmProperty key members are not supported"); var spr = new SimplePropertyRef(p); yield return(spr); } }
internal DiscriminatorMapInfo(EntityTypeBase rootEntityType, bool includesSubTypes, ExplicitDiscriminatorMap discriminatorMap) { RootEntityType = rootEntityType; IncludesSubTypes = includesSubTypes; DiscriminatorMap = discriminatorMap; }
internal RefType(EntityType entityType) : base(RefType.GetIdentity((EntityTypeBase)Check.NotNull <EntityType>(entityType, nameof(entityType))), "Transient", entityType.DataSpace) { this._elementType = (EntityTypeBase)entityType; this.SetReadOnly(); }
private static AssociationType ConvertToAssociationType( Relationship element, DbProviderManifest providerManifest, Converter.ConversionCache convertedItemCache, Dictionary <SchemaElement, GlobalItem> newGlobalItems) { AssociationType associationType = new AssociationType(element.Name, element.Namespace, element.IsForeignKey, Converter.GetDataSpace(providerManifest)); newGlobalItems.Add((SchemaElement)element, (GlobalItem)associationType); foreach (RelationshipEnd end in (IEnumerable <IRelationshipEnd>)element.Ends) { EntityType endMemberType = (EntityType)Converter.LoadSchemaElement((System.Data.Entity.Core.SchemaObjectModel.SchemaType)end.Type, providerManifest, convertedItemCache, newGlobalItems); AssociationEndMember associationEndMember = Converter.InitializeAssociationEndMember(associationType, (IRelationshipEnd)end, endMemberType); Converter.AddOtherContent((SchemaElement)end, (MetadataItem)associationEndMember); foreach (OnOperation operation in (IEnumerable <OnOperation>)end.Operations) { if (operation.Operation == Operation.Delete) { OperationAction operationAction = OperationAction.None; switch (operation.Action) { case System.Data.Entity.Core.SchemaObjectModel.Action.None: operationAction = OperationAction.None; break; case System.Data.Entity.Core.SchemaObjectModel.Action.Cascade: operationAction = OperationAction.Cascade; break; } associationEndMember.DeleteBehavior = operationAction; } } if (end.Documentation != null) { associationEndMember.Documentation = Converter.ConvertToDocumentation(end.Documentation); } } for (int index = 0; index < element.Constraints.Count; ++index) { System.Data.Entity.Core.SchemaObjectModel.ReferentialConstraint constraint = element.Constraints[index]; AssociationEndMember member1 = (AssociationEndMember)associationType.Members[constraint.PrincipalRole.Name]; AssociationEndMember member2 = (AssociationEndMember)associationType.Members[constraint.DependentRole.Name]; EntityTypeBase elementType1 = ((RefType)member1.TypeUsage.EdmType).ElementType; EntityTypeBase elementType2 = ((RefType)member2.TypeUsage.EdmType).ElementType; ReferentialConstraint referentialConstraint = new ReferentialConstraint((RelationshipEndMember)member1, (RelationshipEndMember)member2, (IEnumerable <EdmProperty>)Converter.GetProperties(elementType1, constraint.PrincipalRole.RoleProperties), (IEnumerable <EdmProperty>)Converter.GetProperties(elementType2, constraint.DependentRole.RoleProperties)); if (constraint.Documentation != null) { referentialConstraint.Documentation = Converter.ConvertToDocumentation(constraint.Documentation); } if (constraint.PrincipalRole.Documentation != null) { referentialConstraint.FromRole.Documentation = Converter.ConvertToDocumentation(constraint.PrincipalRole.Documentation); } if (constraint.DependentRole.Documentation != null) { referentialConstraint.ToRole.Documentation = Converter.ConvertToDocumentation(constraint.DependentRole.Documentation); } associationType.AddReferentialConstraint(referentialConstraint); Converter.AddOtherContent((SchemaElement)element.Constraints[index], (MetadataItem)referentialConstraint); } if (element.Documentation != null) { associationType.Documentation = Converter.ConvertToDocumentation(element.Documentation); } Converter.AddOtherContent((SchemaElement)element, (MetadataItem)associationType); return(associationType); }
/// <summary> /// If the discrminator map we're already tracking for this type (in this entityset) /// isn't already rooted at our required type, then we have to suppress the use of /// the descriminator maps when we constrct the structuredtypes; see SQLBUDT #615744 /// </summary> private void DetermineDiscriminatorMapUsage( Node viewNode, EntitySetBase entitySet, EntityTypeBase rootEntityType, bool includeSubtypes) { ExplicitDiscriminatorMap discriminatorMap = null; // we expect the view to be capped with a project; we're just being careful here. if (viewNode.Op.OpType == OpType.Project) { var discriminatedNewEntityOp = viewNode.Child1.Child0.Child0.Op as DiscriminatedNewEntityOp; if (null != discriminatedNewEntityOp) { discriminatorMap = discriminatedNewEntityOp.DiscriminatorMap; } } DiscriminatorMapInfo discriminatorMapInfo; if (!m_discriminatorMaps.TryGetValue(entitySet, out discriminatorMapInfo)) { if (null == rootEntityType) { rootEntityType = entitySet.ElementType; includeSubtypes = true; } discriminatorMapInfo = new DiscriminatorMapInfo(rootEntityType, includeSubtypes, discriminatorMap); m_discriminatorMaps.Add(entitySet, discriminatorMapInfo); } else { discriminatorMapInfo.Merge(rootEntityType, includeSubtypes, discriminatorMap); } }
private static bool IsTableSplitDependent(EntityTypeBase entityTypeBase, DbDatabaseMapping databaseMapping) { DebugCheck.NotNull(entityTypeBase); var associationType = databaseMapping .Model.AssociationTypes .SingleOrDefault( at => at.IsForeignKey && at.IsRequiredToRequired() && !at.IsSelfReferencing() && (at.SourceEnd.GetEntityType().IsAssignableFrom(entityTypeBase) || at.TargetEnd.GetEntityType().IsAssignableFrom(entityTypeBase)) && databaseMapping.Database.AssociationTypes .All(fk => fk.Name != at.Name)); // no store FK == shared table return associationType != null && associationType.TargetEnd.GetEntityType() == entityTypeBase; }
private ModificationFunctionMapping GenerateFunctionMapping( ModificationOperator modificationOperator, EntitySetBase entitySetBase, EntityTypeBase entityTypeBase, DbDatabaseMapping databaseMapping, IEnumerable<EdmProperty> parameterProperties, IEnumerable<Tuple<ModificationFunctionMemberPath, EdmProperty>> iaFkProperties, IList<ColumnMappingBuilder> columnMappings, IEnumerable<EdmProperty> resultProperties = null, string functionNamePrefix = null) { DebugCheck.NotNull(entitySetBase); DebugCheck.NotNull(entityTypeBase); DebugCheck.NotNull(databaseMapping); DebugCheck.NotNull(parameterProperties); DebugCheck.NotNull(iaFkProperties); DebugCheck.NotNull(columnMappings); var useOriginalValues = modificationOperator == ModificationOperator.Delete; var parameterMappingGenerator = new FunctionParameterMappingGenerator(_providerManifest); var parameterBindings = parameterMappingGenerator .Generate( modificationOperator == ModificationOperator.Insert && IsTableSplitDependent(entityTypeBase, databaseMapping) ? ModificationOperator.Update : modificationOperator, parameterProperties, columnMappings, new List<EdmProperty>(), useOriginalValues) .Concat( parameterMappingGenerator .Generate(iaFkProperties, useOriginalValues)) .ToList(); var parameters = parameterBindings.Select(b => b.Parameter).ToList(); UniquifyParameterNames(parameters); var functionPayload = new EdmFunctionPayload { ReturnParameters = new FunctionParameter[0], Parameters = parameters.ToArray(), IsComposable = false }; var function = databaseMapping.Database .AddFunction( (functionNamePrefix ?? entityTypeBase.Name) + "_" + modificationOperator.ToString(), functionPayload); var functionMapping = new ModificationFunctionMapping( entitySetBase, entityTypeBase, function, parameterBindings, null, resultProperties != null ? resultProperties.Select( p => new ModificationFunctionResultBinding( columnMappings.First(cm => cm.PropertyPath.SequenceEqual(new[] { p })).ColumnProperty.Name, p)) : null); return functionMapping; }
// <summary> // Tries to generate the Oftype or OfTypeOnly query view for a given entity set and type. // Returns false if the view could not be generated. // Possible reasons for failing are // 1) Passing in OfTypeOnly on an abstract type // 2) In user-specified query views mode a query for the given type is absent // </summary> internal bool TryGetGeneratedViewOfType( EntitySetBase entity, EntityTypeBase type, bool includeSubtypes, out GeneratedView generatedView) { var key = new OfTypeQVCacheKey(entity, new Pair<EntityTypeBase, bool>(type, includeSubtypes)); generatedView = _generatedViewOfTypeMemoizer.Evaluate(key); return (generatedView != null); }
// <summary> // this method will be called in metadatworkspace, the signature is the same as the one in ViewDictionary // </summary> internal bool TryGetGeneratedViewOfType( EntitySetBase entity, EntityTypeBase type, bool includeSubtypes, out GeneratedView generatedView) { return m_viewDictionary.TryGetGeneratedViewOfType(entity, type, includeSubtypes, out generatedView); }
// <summary> // Entry point for Type specific generation of Query Views // </summary> internal static ViewGenResults GenerateTypeSpecificQueryView( EntityContainerMapping containerMapping, ConfigViewGenerator config, EntitySetBase entity, EntityTypeBase type, bool includeSubtypes, out bool success) { DebugCheck.NotNull(containerMapping); DebugCheck.NotNull(config); DebugCheck.NotNull(entity); DebugCheck.NotNull(type); Debug.Assert(!type.Abstract, "Can not generate OfType/OfTypeOnly query view for and abstract type"); if (config.IsNormalTracing) { Helpers.StringTraceLine(""); Helpers.StringTraceLine( "<<<<<<<< Generating Query View for Entity [" + entity.Name + "] OfType" + (includeSubtypes ? "" : "Only") + "(" + type.Name + ") >>>>>>>"); } if (containerMapping.GetEntitySetMapping(entity.Name).QueryView != null) { //Type-specific QV does not exist in the cache, but // there is a EntitySet QV. So we can't generate the view (no mapping exists for this EntitySet) // and we rely on Query to call us again to get the EntitySet View. success = false; return null; } //Compute Cell Groups or get it from Memoizer var args = new InputForComputingCellGroups(containerMapping, config); var result = containerMapping.GetCellgroups(args); success = result.Success; if (!success) { return null; } var foreignKeyConstraints = result.ForeignKeyConstraints; // Get a Clone of cell groups from cache since cells are modified during viewgen, and we dont want the cached copy to change var cellGroups = result.CellGroups.Select(setOfcells => new CellGroup(setOfcells.Select(cell => new Cell(cell)))).ToList(); var cells = result.Cells; var identifiers = result.Identifiers; var viewGenResults = new ViewGenResults(); var tmpLog = EnsureAllCSpaceContainerSetsAreMapped(cells, containerMapping); if (tmpLog.Count > 0) { viewGenResults.AddErrors(tmpLog); Helpers.StringTraceLine(viewGenResults.ErrorsToString()); success = true; //atleast we tried successfully return viewGenResults; } foreach (var cellGroup in cellGroups) { if (!DoesCellGroupContainEntitySet(cellGroup, entity)) { continue; } ViewGenerator viewGenerator = null; var groupErrorLog = new ErrorLog(); try { viewGenerator = new ViewGenerator(cellGroup, config, foreignKeyConstraints, containerMapping); } catch (InternalMappingException exception) { // All exceptions have mapping errors in them Debug.Assert(exception.ErrorLog.Count > 0, "Incorrectly created mapping exception"); groupErrorLog = exception.ErrorLog; } if (groupErrorLog.Count > 0) { break; } Debug.Assert(viewGenerator != null); //make sure there is no exception thrown that does not add error to log var mode = includeSubtypes ? ViewGenMode.OfTypeViews : ViewGenMode.OfTypeOnlyViews; groupErrorLog = viewGenerator.GenerateQueryViewForSingleExtent(viewGenResults.Views, identifiers, entity, type, mode); if (groupErrorLog.Count != 0) { viewGenResults.AddErrors(groupErrorLog); } } success = true; return viewGenResults; }
internal static IEnumerable <EntityTypeModificationFunctionMapping> GetModificationFunctionMappingsForEntitySetAndType( StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase entityType) { var containerMapping = GetEntityContainerMap(mappingCollection, container); var extentMap = containerMapping.GetSetMapping(entitySet.Name); var entitySetMapping = extentMap as EntitySetMapping; //The Set may have no mapping if (entitySetMapping != null) { if (entitySetMapping != null) //could be association set mapping { foreach ( var v in entitySetMapping.ModificationFunctionMappings.Where(functionMap => functionMap.EntityType.Equals(entityType))) { yield return(v); } } } }
protected override void Visit(EntityTypeBase entityTypeBase) { base.Visit(entityTypeBase); }
/// <summary> /// Return members for MetdataWorkspace.GetRequiredOriginalValueMembers() and MetdataWorkspace.GetRelevantMembersForUpdate() methods. /// </summary> /// <param name="entitySet"> An EntitySet belonging to the C-Space. Must not be null. </param> /// <param name="entityType"> An EntityType that participates in the given EntitySet. Must not be null. </param> /// <param name="interestingMembersKind"> Scenario the members should be returned for. </param> /// <returns> ReadOnlyCollection of interesting members for the requested scenario ( <paramref /// name="interestingMembersKind" /> ). </returns> internal ReadOnlyCollection<EdmMember> GetInterestingMembers( EntitySetBase entitySet, EntityTypeBase entityType, InterestingMembersKind interestingMembersKind) { Debug.Assert(entitySet != null, "entitySet != null"); Debug.Assert(entityType != null, "entityType != null"); var key = new Tuple<EntitySetBase, EntityTypeBase, InterestingMembersKind>(entitySet, entityType, interestingMembersKind); return _cachedInterestingMembers.GetOrAdd(key, FindInterestingMembers(entitySet, entityType, interestingMembersKind)); }
// <summary> // Finds interesting members for MetdataWorkspace.GetRequiredOriginalValueMembers() and MetdataWorkspace.GetRelevantMembersForUpdate() methods // for the given <paramref name="entitySet" /> and <paramref name="entityType" />. // </summary> // <param name="entitySet"> An EntitySet belonging to the C-Space. Must not be null. </param> // <param name="entityType"> An EntityType that participates in the given EntitySet. Must not be null. </param> // <param name="interestingMembersKind"> Scenario the members should be returned for. </param> // <returns> // ReadOnlyCollection of interesting members for the requested scenario ( // <paramref // name="interestingMembersKind" /> // ). // </returns> private ReadOnlyCollection<EdmMember> FindInterestingMembers( EntitySetBase entitySet, EntityTypeBase entityType, InterestingMembersKind interestingMembersKind) { DebugCheck.NotNull(entitySet); DebugCheck.NotNull(entityType); var interestingMembers = new List<EdmMember>(); foreach ( var storageTypeMapping in MappingMetadataHelper.GetMappingsForEntitySetAndSuperTypes(this, entitySet.EntityContainer, entitySet, entityType)) { var associationTypeMapping = storageTypeMapping as AssociationTypeMapping; if (associationTypeMapping != null) { FindInterestingAssociationMappingMembers(associationTypeMapping, interestingMembers); } else { Debug.Assert(storageTypeMapping is EntityTypeMapping, "EntityTypeMapping expected."); FindInterestingEntityMappingMembers( (EntityTypeMapping)storageTypeMapping, interestingMembersKind, interestingMembers); } } // For backwards compatibility we don't return foreign keys from the obsolete MetadataWorkspace.GetRequiredOriginalValueMembers() method if (interestingMembersKind != InterestingMembersKind.RequiredOriginalValueMembers) { FindForeignKeyProperties(entitySet, entityType, interestingMembers); } foreach (var functionMappings in MappingMetadataHelper .GetModificationFunctionMappingsForEntitySetAndType(this, entitySet.EntityContainer, entitySet, entityType) .Where(functionMappings => functionMappings.UpdateFunctionMapping != null)) { FindInterestingFunctionMappingMembers(functionMappings, interestingMembersKind, ref interestingMembers); } Debug.Assert(interestingMembers != null, "interestingMembers must never be null."); return new ReadOnlyCollection<EdmMember>(interestingMembers.Distinct().ToList()); }
internal ErrorLog GenerateQueryViewForSingleExtent( ViewSet views, CqlIdentifiers identifiers, EntitySetBase entity, EntityTypeBase type, ViewGenMode mode) { Debug.Assert(mode != ViewGenMode.GenerateAllViews); if (m_config.IsNormalTracing) { var builder = new StringBuilder(); Cell.CellsToBuilder(builder, m_cellGroup); Helpers.StringTraceLine(builder.ToString()); } // Check if the cellgroup is consistent and all known S constraints are // satisified by the known C constraints var validator = new CellGroupValidator(m_cellGroup, m_config); var errorLog = validator.Validate(); if (errorLog.Count > 0) { errorLog.PrintTrace(); return errorLog; } // Make sure that the foreign key constraints are not violated if (m_config.IsValidationEnabled) { CheckForeignKeyConstraints(errorLog); } if (errorLog.Count > 0) { errorLog.PrintTrace(); return errorLog; // If we have discovered errors here, do not generate query views } // For the S-side, we add NOT ... for each scalar constant so // that if we have C, P in the mapping but the store has C, P, S, // we can handle it in the query views m_updateDomainMap.ExpandDomainsToIncludeAllPossibleValues(); foreach (var cell in m_cellGroup) { cell.SQuery.WhereClause.FixDomainMap(m_updateDomainMap); } errorLog = GenerateQueryViewForExtentAndType(identifiers, views, entity, type, mode); return errorLog; }
// <summary> // Finds foreign key properties and adds them to the <paramref name="interestingMembers" />. // </summary> // <param name="entitySetBase"> // Entity set <paramref name="entityType" /> relates to. Must not be null. // </param> // <param name="entityType"> Entity type for which to find foreign key properties. Must not be null. </param> // <param name="interestingMembers"> The list the interesting members (if any) will be added to. Must not be null. </param> private static void FindForeignKeyProperties( EntitySetBase entitySetBase, EntityTypeBase entityType, List<EdmMember> interestingMembers) { var entitySet = entitySetBase as EntitySet; if (entitySet != null && entitySet.HasForeignKeyRelationships) { // (6) Foreign keys // select all foreign key properties defined on the entityType and all its ancestors interestingMembers.AddRange( MetadataHelper.GetTypeAndParentTypesOf(entityType, true) .SelectMany(e => ((EntityType)e).Properties) .Where(p => entitySet.ForeignKeyDependents.SelectMany(fk => fk.Item2.ToProperties).Contains(p))); } }
private static EdmProperty[] GetProperties(EntityTypeBase entityType, IList<Som.PropertyRefElement> properties) { Debug.Assert(properties.Count != 0); var result = new EdmProperty[properties.Count]; for (var i = 0; i < properties.Count; i++) { result[i] = (EdmProperty)entityType.Members[properties[i].Name]; } return result; }
// <summary> // Generates a single query view for a given Extent and type. It is used to generate OfType and OfTypeOnly views. // </summary> // <param name="includeSubtypes"> Whether the view should include extents that are subtypes of the given entity </param> private bool TryGenerateQueryViewOfType( EntityContainer entityContainer, EntitySetBase entity, EntityTypeBase type, bool includeSubtypes, out GeneratedView generatedView) { DebugCheck.NotNull(entityContainer); DebugCheck.NotNull(entity); DebugCheck.NotNull(type); if (type.Abstract) { generatedView = null; return false; } //Get the mapping that has the entity container mapped. var entityContainerMap = MappingMetadataHelper.GetEntityContainerMap(_storageMappingItemCollection, entityContainer); Debug.Assert(!entityContainerMap.IsEmpty, "There are no entity set maps"); bool success; var viewGenResults = ViewgenGatekeeper.GenerateTypeSpecificQueryView( entityContainerMap, _config, entity, type, includeSubtypes, out success); if (!success) { generatedView = null; return false; //could not generate view } var extentMappingViews = viewGenResults.Views; if (viewGenResults.HasErrors) { throw new MappingException(Helper.CombineErrorMessage(viewGenResults.Errors)); } Debug.Assert(extentMappingViews.AllValues.Count() == 1, "Viewgen should have produced only one view"); generatedView = extentMappingViews.AllValues.First(); return true; }
private static Type GetClrType(MetadataWorkspace metadata, ObjectItemCollection objectItemCollection, EntityTypeBase type) { return metadata .GetItems<EntityType>(DataSpace.OSpace) .Select(objectItemCollection.GetClrType) .Single(e => e.Name == type.Name); }
// <summary> // Return members for MetdataWorkspace.GetRequiredOriginalValueMembers() and MetdataWorkspace.GetRelevantMembersForUpdate() methods. // </summary> // <param name="entitySet"> An EntitySet belonging to the C-Space. Must not be null. </param> // <param name="entityType"> An EntityType that participates in the given EntitySet. Must not be null. </param> // <param name="interestingMembersKind"> Scenario the members should be returned for. </param> // <returns> // ReadOnlyCollection of interesting members for the requested scenario ( // <paramref // name="interestingMembersKind" /> // ). // </returns> internal ReadOnlyCollection<EdmMember> GetInterestingMembers( EntitySetBase entitySet, EntityTypeBase entityType, InterestingMembersKind interestingMembersKind) { DebugCheck.NotNull(entitySet); DebugCheck.NotNull(entityType); var key = new Tuple<EntitySetBase, EntityTypeBase, InterestingMembersKind>(entitySet, entityType, interestingMembersKind); return _cachedInterestingMembers.GetOrAdd(key, FindInterestingMembers(entitySet, entityType, interestingMembersKind)); }
// <summary> // Get the rel properties declared by this type (and *not* by any of its subtypes) // </summary> // <param name="entityType"> the entity type </param> // <returns> set of rel properties declared for this type </returns> internal IEnumerable<RelProperty> GetDeclaredOnlyRelProperties(EntityTypeBase entityType) { List<RelProperty> relProperties; if (_relPropertyMap.TryGetValue(entityType, out relProperties)) { foreach (var p in relProperties) { yield return p; } } yield break; }
protected virtual void Visit(EntityTypeBase entityTypeBase) { // switching node if (entityTypeBase == null) { return; } switch (entityTypeBase.BuiltInTypeKind) { case BuiltInTypeKind.AssociationType: Visit((AssociationType)entityTypeBase); break; case BuiltInTypeKind.EntityType: Visit((EntityType)entityTypeBase); break; default: Debug.Fail( String.Format( CultureInfo.InvariantCulture, "Found type '{0}', did we add a new type?", entityTypeBase.BuiltInTypeKind)); break; } }
// <summary> // Get the rel-properties of this entity and its supertypes (starting from the root) // </summary> // <param name="entityType"> the entity type </param> // <returns> set of rel-properties for this entity type (and its supertypes) </returns> internal IEnumerable<RelProperty> GetRelProperties(EntityTypeBase entityType) { if (entityType.BaseType != null) { foreach (var p in GetRelProperties(entityType.BaseType as EntityTypeBase)) { yield return p; } } foreach (var p in GetDeclaredOnlyRelProperties(entityType)) { yield return p; } }
private ErrorLog GenerateQueryViewForExtentAndType( CqlIdentifiers identifiers, ViewSet views, EntitySetBase entity, EntityTypeBase type, ViewGenMode mode) { Debug.Assert(mode != ViewGenMode.GenerateAllViews); // Keep track of the mapping exceptions that we have generated var errorLog = new ErrorLog(); if (m_config.IsViewTracing) { Helpers.StringTraceLine(String.Empty); Helpers.StringTraceLine(String.Empty); Helpers.FormatTraceLine( "================= Generating {0} Query View for: {1} ===========================", (mode == ViewGenMode.OfTypeViews) ? "OfType" : "OfTypeOnly", entity.Name); Helpers.StringTraceLine(String.Empty); Helpers.StringTraceLine(String.Empty); } try { // (1) view generation (checks that extents are fully mapped) var context = CreateViewgenContext(entity, ViewTarget.QueryView, identifiers); var queryRewriter = GenerateViewsForExtentAndType(type, context, identifiers, views, mode); } catch (InternalMappingException exception) { // All exceptions have mapping errors in them Debug.Assert(exception.ErrorLog.Count > 0, "Incorrectly created mapping exception"); errorLog.Merge(exception.ErrorLog); } return errorLog; }
internal static IEnumerable <TypeMapping> GetMappingsForEntitySetAndType( StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase entityType) { DebugCheck.NotNull(entityType); var containerMapping = GetEntityContainerMap(mappingCollection, container); var extentMap = containerMapping.GetSetMapping(entitySet.Name); //The Set may have no mapping if (extentMap != null) { //for each mapping fragment of Type we are interested in within the given set //Check use of IsOfTypes in Code review foreach (var typeMap in extentMap.TypeMappings.Where(map => map.Types.Union(map.IsOfTypes).Contains(entityType))) { yield return(typeMap); } } }