internal static TypeUsage ValidateNewEntityWithRelationships( EntityType entityType, IEnumerable <DbExpression> attributeValues, IList <DbRelatedEntityRef> relationships, out DbExpressionList validArguments, out ReadOnlyCollection <DbRelatedEntityRef> validRelatedRefs) { TypeUsage typeUsage = ArgumentValidation.ValidateNew(ArgumentValidation.CreateResultType((EdmType)entityType), attributeValues, out validArguments); if (relationships.Count > 0) { List <DbRelatedEntityRef> relatedEntityRefList = new List <DbRelatedEntityRef>(relationships.Count); for (int index = 0; index < relationships.Count; ++index) { DbRelatedEntityRef relationship = relationships[index]; EntityTypeBase elementType = TypeHelpers.GetEdmType <RefType>(relationship.SourceEnd.TypeUsage).ElementType; if (!entityType.EdmEquals((MetadataItem)elementType) && !entityType.IsSubtypeOf((EdmType)elementType)) { throw new ArgumentException(Strings.Cqt_NewInstance_IncompatibleRelatedEntity_SourceTypeNotValid, StringUtil.FormatIndex(nameof(relationships), index)); } relatedEntityRefList.Add(relationship); } validRelatedRefs = new ReadOnlyCollection <DbRelatedEntityRef>((IList <DbRelatedEntityRef>)relatedEntityRefList); } else { validRelatedRefs = new ReadOnlyCollection <DbRelatedEntityRef>((IList <DbRelatedEntityRef>) new DbRelatedEntityRef[0]); } return(typeUsage); }
internal DbRelatedEntityRef( RelationshipEndMember sourceEnd, RelationshipEndMember targetEnd, DbExpression targetEntityRef) { if (!object.ReferenceEquals((object)sourceEnd.DeclaringType, (object)targetEnd.DeclaringType)) { throw new ArgumentException(Strings.Cqt_RelatedEntityRef_TargetEndFromDifferentRelationship, nameof(targetEnd)); } if (object.ReferenceEquals((object)sourceEnd, (object)targetEnd)) { throw new ArgumentException(Strings.Cqt_RelatedEntityRef_TargetEndSameAsSourceEnd, nameof(targetEnd)); } if (targetEnd.RelationshipMultiplicity != RelationshipMultiplicity.One && targetEnd.RelationshipMultiplicity != RelationshipMultiplicity.ZeroOrOne) { throw new ArgumentException(Strings.Cqt_RelatedEntityRef_TargetEndMustBeAtMostOne, nameof(targetEnd)); } if (!TypeSemantics.IsReferenceType(targetEntityRef.ResultType)) { throw new ArgumentException(Strings.Cqt_RelatedEntityRef_TargetEntityNotRef, nameof(targetEntityRef)); } EntityTypeBase elementType1 = TypeHelpers.GetEdmType <RefType>(targetEnd.TypeUsage).ElementType; EntityTypeBase elementType2 = TypeHelpers.GetEdmType <RefType>(targetEntityRef.ResultType).ElementType; if (!elementType1.EdmEquals((MetadataItem)elementType2) && !TypeSemantics.IsSubTypeOf((EdmType)elementType2, (EdmType)elementType1)) { throw new ArgumentException(Strings.Cqt_RelatedEntityRef_TargetEntityNotCompatible, nameof(targetEntityRef)); } this._targetEntityRef = targetEntityRef; this._targetEnd = targetEnd; this._sourceEnd = sourceEnd; }
private void CheckConcurrencyControlTokens() { EntityTypeBase elementType = this.m_extent.ElementType; Set <EdmMember> forTypeHierarchy = MetadataHelper.GetConcurrencyMembersForTypeHierarchy(elementType, this.m_edmItemCollection); Set <MemberPath> other = new Set <MemberPath>(MemberPath.EqualityComparer); foreach (EdmMember member in forTypeHierarchy) { if (!member.DeclaringType.IsAssignableFrom((EdmType)elementType)) { ExceptionHelpers.ThrowMappingException(new ErrorLog.Record(ViewGenErrorCode.ConcurrencyDerivedClass, Strings.ViewGen_Concurrency_Derived_Class((object)member.Name, (object)member.DeclaringType.Name, (object)this.m_extent), (IEnumerable <LeftCellWrapper>) this.m_cellWrappers, string.Empty), this.m_config); } other.Add(new MemberPath(this.m_extent, member)); } if (forTypeHierarchy.Count <= 0) { return; } foreach (LeftCellWrapper cellWrapper in this.m_cellWrappers) { Set <MemberPath> set = new Set <MemberPath>(cellWrapper.OnlyInputCell.CQuery.WhereClause.MemberRestrictions.Select <MemberRestriction, MemberPath>((Func <MemberRestriction, MemberPath>)(oneOf => oneOf.RestrictedMemberSlot.MemberPath)), MemberPath.EqualityComparer); set.Intersect(other); if (set.Count > 0) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(Strings.ViewGen_Concurrency_Invalid_Condition((object)MemberPath.PropertiesToUserString((IEnumerable <MemberPath>)set, false), (object)this.m_extent.Name)); ExceptionHelpers.ThrowMappingException(new ErrorLog.Record(ViewGenErrorCode.ConcurrencyTokenHasCondition, stringBuilder.ToString(), (IEnumerable <LeftCellWrapper>) new LeftCellWrapper[1] { cellWrapper }, string.Empty), this.m_config); } } }
private void AddEntityTypeToSetEntry(EntityType entityType, EntitySet entitySet) { EntityTypeBase rootType = StructuredTypeInfo.GetRootType((EntityTypeBase)entityType); bool flag = true; if (entitySet == null) { flag = false; } else { EntitySet entitySet1; if (this.m_entityTypeToEntitySetMap.TryGetValue(rootType, out entitySet1) && entitySet1 != entitySet) { flag = false; } } if (flag) { this.m_entityTypeToEntitySetMap[rootType] = entitySet; } else { this.m_entityTypeToEntitySetMap[rootType] = (EntitySet)null; } }
/// <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; } } }
public override void Visit(DbScanExpression scanExpression) { string str = SqlGenerator.GetTargetTSql(scanExpression.Target) + " AS " + (this._currentTableAlias = "t" + (object)this._aliasCount++); EntityTypeBase elementType = scanExpression.Target.ElementType; if (this._from.Length == 0) { this._baseTable = (EntityType)elementType; this._from.Append("FROM "); this._from.Append(str); } else { this._from.AppendLine(); this._from.Append("JOIN "); this._from.Append(str); this._from.Append(" ON "); for (int index = 0; index < elementType.KeyMembers.Count; ++index) { if (index > 0) { this._from.Append(" AND "); } this._from.Append(this._currentTableAlias + "."); this._from.Append(SqlGenerator.QuoteIdentifier(elementType.KeyMembers[index].Name)); this._from.Append(" = t0."); this._from.Append(SqlGenerator.QuoteIdentifier(this._baseTable.KeyMembers[index].Name)); } } }
/// <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()); }
/// <summary> /// Creates metadata for a new row type with column names and types based on the key members of the specified Entity type /// </summary> /// <param name="entityType"> The Entity type that provides the Key members on which the column names and types of the new row type will be based </param> /// <returns> A new RowType info with column names and types corresponding to the Key members of the specified Entity type </returns> internal static RowType CreateKeyRowType(EntityTypeBase entityType) { IEnumerable <EdmMember> entityKeys = entityType.KeyMembers; if (null == entityKeys) { throw new ArgumentException(Strings.Cqt_Metadata_EntityTypeNullKeyMembersInvalid, "entityType"); } var resultCols = new List <KeyValuePair <string, TypeUsage> >(); //int idx = 0; foreach (EdmProperty keyProperty in entityKeys) { //this.CheckMember(keyProperty, "property", CommandTreeUtils.FormatIndex("entityType.KeyMembers", idx++)); resultCols.Add(new KeyValuePair <string, TypeUsage>(keyProperty.Name, Helper.GetModelTypeUsage(keyProperty))); } if (resultCols.Count < 1) { throw new ArgumentException(Strings.Cqt_Metadata_EntityTypeEmptyKeyMembersInvalid, "entityType"); } return(CreateRowType(resultCols)); }
/// <summary> /// Compara que los items de ambas listas sean los mismos /// </summary> /// <param name="lstNew">Lista Nueva</param> /// <param name="lstOld">Lista Antigua</param> /// <returns>True. Contienen los mismos registro | False.Tienen registros diferentes</returns> /// <history> /// [emoguel] created 15/04/2016 /// [emoguel] Modified--Ignora registros vacios y verifica si las lista son null /// </history> public static bool IsListEquals <T>(List <T> lstNew, List <T> lstOld, string id = "") { if (lstNew != null && lstOld != null) { Type type = typeof(T); #region Obtener la llave primaria if (id == "") { EntityTypeBase entityTypeBase = EntityHelper.GetEntityTypeBase(type); //Obtenemos las propiedades de la entidad EdmMember edmMember = entityTypeBase.KeyMembers.FirstOrDefault(); //Obtenemos la llave primaria id = edmMember.Name; } var lst1 = lstNew.Where(p => !lstOld.Any(p1 => type.GetProperty(id).GetValue(p1) == type.GetProperty(id).GetValue(p)) && type.GetProperty(id).GetValue(p) != null).ToList(); var lst2 = lstOld.Where(p => !lstNew.Any(p1 => type.GetProperty(id).GetValue(p1) == type.GetProperty(id).GetValue(p)) && type.GetProperty(id).GetValue(p) != null).ToList(); #endregion if (lst1.Count() > 0 || lst2.Count() > 0) { return(false); } } return(true); }
internal StorageModificationFunctionMapping( EntitySetBase entitySet, EntityTypeBase entityType, EdmFunction function, IEnumerable <StorageModificationFunctionParameterBinding> parameterBindings, FunctionParameter rowsAffectedParameter, IEnumerable <StorageModificationFunctionResultBinding> resultBindings) { EntityUtil.CheckArgumentNull(entitySet, "entitySet"); this.Function = EntityUtil.CheckArgumentNull(function, "function"); this.RowsAffectedParameter = rowsAffectedParameter; this.ParameterBindings = EntityUtil.CheckArgumentNull(parameterBindings, "parameterBindings") .ToList().AsReadOnly(); if (null != resultBindings) { List <StorageModificationFunctionResultBinding> bindings = resultBindings.ToList(); if (0 < bindings.Count) { ResultBindings = bindings.AsReadOnly(); } } this.CollocatedAssociationSetEnds = GetReferencedAssociationSetEnds(entitySet as EntitySet, entityType as EntityType, parameterBindings) .ToList() .AsReadOnly(); }
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) { bool useOriginalValues = modificationOperator == ModificationOperator.Delete; FunctionParameterMappingGenerator mappingGenerator = new FunctionParameterMappingGenerator(this._providerManifest); List <ModificationFunctionParameterBinding> list1 = mappingGenerator.Generate(modificationOperator != ModificationOperator.Insert || !ModificationFunctionMappingGenerator.IsTableSplitDependent(entityTypeBase, databaseMapping) ? modificationOperator : ModificationOperator.Update, parameterProperties, columnMappings, (IList <EdmProperty>) new List <EdmProperty>(), useOriginalValues).Concat <ModificationFunctionParameterBinding>(mappingGenerator.Generate(iaFkProperties, useOriginalValues)).ToList <ModificationFunctionParameterBinding>(); List <FunctionParameter> list2 = list1.Select <ModificationFunctionParameterBinding, FunctionParameter>((Func <ModificationFunctionParameterBinding, FunctionParameter>)(b => b.Parameter)).ToList <FunctionParameter>(); ModificationFunctionMappingGenerator.UniquifyParameterNames((IList <FunctionParameter>)list2); EdmFunctionPayload functionPayload = new EdmFunctionPayload() { ReturnParameters = (IList <FunctionParameter>) new FunctionParameter[0], Parameters = (IList <FunctionParameter>)list2.ToArray(), IsComposable = new bool?(false) }; EdmFunction function = databaseMapping.Database.AddFunction((functionNamePrefix ?? entityTypeBase.Name) + "_" + modificationOperator.ToString(), functionPayload); return(new ModificationFunctionMapping(entitySetBase, entityTypeBase, function, (IEnumerable <ModificationFunctionParameterBinding>)list1, (FunctionParameter)null, resultProperties != null ? resultProperties.Select <EdmProperty, ModificationFunctionResultBinding>((Func <EdmProperty, ModificationFunctionResultBinding>)(p => new ModificationFunctionResultBinding(columnMappings.First <ColumnMappingBuilder>((Func <ColumnMappingBuilder, bool>)(cm => cm.PropertyPath.SequenceEqual <EdmProperty>((IEnumerable <EdmProperty>) new EdmProperty[1] { p }))).ColumnProperty.Name, p))) : (IEnumerable <ModificationFunctionResultBinding>)null)); }
/// <summary> /// Returns a string of the form "a.b.c" that corresponds to the items in the path. This string can be used for tests or localization. /// If <paramref name="forAlias"/>=true, we return a string that is relevant for Cql aliases, else we return the exact path. /// </summary> internal string PathToString(bool?forAlias) { StringBuilder builder = new StringBuilder(); if (forAlias != null) { if (forAlias == true) { // For the 0th entry, we just choose the type of the element in // which the first entry belongs, e.g., if Addr belongs to CCustomer, // we choose CCustomer and not CPerson. if (m_path.Count == 0) { EntityTypeBase type = m_extent.ElementType; return(type.Name); } builder.Append(m_path[0].DeclaringType.Name); // Get CCustomer here } else { // Append the extent name builder.Append(m_extent.Name); } } // Just join the path using "." for (int i = 0; i < m_path.Count; i++) { builder.Append('.'); builder.Append(m_path[i].Name); } return(builder.ToString()); }
private static EntityTypeBase GetEntityType(RelationshipEndMember endMember) { Debug.Assert(endMember.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.RefType, "not a reference type"); EntityTypeBase type = ((RefType)endMember.TypeUsage.EdmType).ElementType; return(type); }
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> /// Add the rel property induced by the specified relationship, (if the target /// end has a multiplicity of one) /// We only keep track of rel-properties that are "interesting" /// </summary> /// <param name="associationType">the association relationship</param> /// <param name="fromEnd">source end of the relationship traversal</param> /// <param name="toEnd">target end of the traversal</param> private void AddRelProperty(AssociationType associationType, AssociationEndMember fromEnd, AssociationEndMember toEnd) { if (toEnd.RelationshipMultiplicity == RelationshipMultiplicity.Many) { return; } RelProperty prop = new RelProperty(associationType, fromEnd, toEnd); if (_interestingRelProperties == null || !_interestingRelProperties.Contains(prop)) { return; } EntityTypeBase entityType = (EntityTypeBase)((RefType)fromEnd.TypeUsage.EdmType).ElementType; List <RelProperty> propList; if (!_relPropertyMap.TryGetValue(entityType, out propList)) { propList = new List <RelProperty>(); _relPropertyMap[entityType] = propList; } propList.Add(prop); }
private void AddRelProperty( AssociationType associationType, AssociationEndMember fromEnd, AssociationEndMember toEnd) { if (toEnd.RelationshipMultiplicity == RelationshipMultiplicity.Many) { return; } RelProperty relProperty = new RelProperty((RelationshipType)associationType, (RelationshipEndMember)fromEnd, (RelationshipEndMember)toEnd); if (this._interestingRelProperties == null || !this._interestingRelProperties.Contains(relProperty)) { return; } EntityTypeBase elementType = ((RefType)fromEnd.TypeUsage.EdmType).ElementType; List <RelProperty> relPropertyList; if (!this._relPropertyMap.TryGetValue(elementType, out relPropertyList)) { relPropertyList = new List <RelProperty>(); this._relPropertyMap[elementType] = relPropertyList; } relPropertyList.Add(relProperty); }
private ErrorLog GenerateQueryViewForExtentAndType( CqlIdentifiers identifiers, KeyToListMap <EntitySetBase, GeneratedView> views, EntitySetBase entity, EntityTypeBase type, ViewGenMode mode) { ErrorLog errorLog = new ErrorLog(); if (this.m_config.IsViewTracing) { Helpers.StringTraceLine(string.Empty); Helpers.StringTraceLine(string.Empty); Helpers.FormatTraceLine("================= Generating {0} Query View for: {1} ===========================", mode == ViewGenMode.OfTypeViews ? (object)"OfType" : (object)"OfTypeOnly", (object)entity.Name); Helpers.StringTraceLine(string.Empty); Helpers.StringTraceLine(string.Empty); } try { ViewgenContext viewgenContext = this.CreateViewgenContext(entity, ViewTarget.QueryView, identifiers); this.GenerateViewsForExtentAndType((EdmType)type, viewgenContext, identifiers, views, mode); } catch (InternalMappingException ex) { errorLog.Merge(ex.ErrorLog); } return(errorLog); }
private static EntityTypeBase GetRootType(EntityTypeBase type) { while (type.BaseType != null) { type = (EntityTypeBase)type.BaseType; } return(type); }
internal DiscriminatorMapInfo( EntityTypeBase rootEntityType, bool includesSubTypes, ExplicitDiscriminatorMap discriminatorMap) { this.RootEntityType = rootEntityType; this.IncludesSubTypes = includesSubTypes; this.DiscriminatorMap = discriminatorMap; }
/// <summary> /// Creates generated view object for the combination of the <paramref name="setMapping"/>.Set and the <paramref name="type"/>. /// This constructor is used for user-defined query views only. /// </summary> internal static bool TryParseUserSpecifiedView(StorageSetMapping setMapping, EntityTypeBase type, string eSQL, bool includeSubtypes, StorageMappingItemCollection mappingItemCollection, ConfigViewGenerator config, /*out*/ IList <EdmSchemaError> errors, out GeneratedView generatedView) { bool failed = false; DbQueryCommandTree commandTree; DiscriminatorMap discriminatorMap; Exception parserException; if (!GeneratedView.TryParseView(eSQL, true, setMapping.Set, mappingItemCollection, config, out commandTree, out discriminatorMap, out parserException)) { EdmSchemaError error = new EdmSchemaError(System.Data.Entity.Strings.Mapping_Invalid_QueryView2(setMapping.Set.Name, parserException.Message), (int)StorageMappingErrorCode.InvalidQueryView, EdmSchemaErrorSeverity.Error, setMapping.EntityContainerMapping.SourceLocation, setMapping.StartLineNumber, setMapping.StartLinePosition, parserException); errors.Add(error); failed = true; } else { Debug.Assert(commandTree != null, "commandTree not set after parsing the view"); // Verify that all expressions appearing in the view are supported. foreach (var error in ViewValidator.ValidateQueryView(commandTree, setMapping, type, includeSubtypes)) { errors.Add(error); failed = true; } // Verify that the result type of the query view is assignable to the element type of the entityset CollectionType queryResultType = (commandTree.Query.ResultType.EdmType) as CollectionType; if ((queryResultType == null) || (!setMapping.Set.ElementType.IsAssignableFrom(queryResultType.TypeUsage.EdmType))) { EdmSchemaError error = new EdmSchemaError(System.Data.Entity.Strings.Mapping_Invalid_QueryView_Type(setMapping.Set.Name), (int)StorageMappingErrorCode.InvalidQueryViewResultType, EdmSchemaErrorSeverity.Error, setMapping.EntityContainerMapping.SourceLocation, setMapping.StartLineNumber, setMapping.StartLinePosition); errors.Add(error); failed = true; } } if (!failed) { generatedView = new GeneratedView(setMapping.Set, type, commandTree, eSQL, discriminatorMap, mappingItemCollection, config); return(true); } else { generatedView = null; return(false); } }
internal ViewExpressionValidator( EntitySetBaseMapping setMapping, EntityTypeBase elementType, bool includeSubtypes) { this._setMapping = setMapping; this._elementType = elementType; this._includeSubtypes = includeSubtypes; this._errors = new List <EdmSchemaError>(); }
internal EntitySet GetEntitySet(EntityTypeBase type) { EntitySet entitySet; if (!this.m_entityTypeToEntitySetMap.TryGetValue(StructuredTypeInfo.GetRootType(type), out entitySet)) { return((EntitySet)null); } return(entitySet); }
internal ViewExpressionValidator(EntitySetBaseMapping setMapping, EntityTypeBase elementType, bool includeSubtypes) { DebugCheck.NotNull(setMapping); DebugCheck.NotNull(elementType); _setMapping = setMapping; _elementType = elementType; _includeSubtypes = includeSubtypes; _errors = new List <EdmSchemaError>(); }
internal ViewExpressionValidator(StorageSetMapping setMapping, EntityTypeBase elementType, bool includeSubtypes) { Debug.Assert(null != setMapping); Debug.Assert(null != elementType); _setMapping = setMapping; _elementType = elementType; _includeSubtypes = includeSubtypes; _errors = new List <EdmSchemaError>(); }
private void GetRequiredSlotsForCaseMember(MemberPath caseMemberPath, bool[] requiredSlots) { CaseStatement caseStatement = this.m_caseStatements[caseMemberPath]; bool flag = false; foreach (CaseStatement.WhenThen clause in caseStatement.Clauses) { clause.Condition.GetRequiredSlots(this.m_projectedSlotMap, requiredSlots); if (!(clause.Value is ConstantProjectedSlot)) { flag = true; } } EdmType edmType = caseMemberPath.EdmType; if (Helper.IsEntityType(edmType) || Helper.IsComplexType(edmType)) { foreach (EdmType instantiatedType in caseStatement.InstantiatedTypes) { foreach (EdmMember structuralMember in (IEnumerable)Helper.GetAllStructuralMembers(instantiatedType)) { int slotIndex = this.GetSlotIndex(caseMemberPath, structuralMember); requiredSlots[slotIndex] = true; } } } else if (caseMemberPath.IsScalarType()) { if (!flag) { return; } int index = this.m_projectedSlotMap.IndexOf(caseMemberPath); requiredSlots[index] = true; } else if (Helper.IsAssociationType(edmType)) { foreach (AssociationEndMember associationEndMember in ((AssociationSet)caseMemberPath.Extent).ElementType.AssociationEndMembers) { int slotIndex = this.GetSlotIndex(caseMemberPath, (EdmMember)associationEndMember); requiredSlots[slotIndex] = true; } } else { EntityTypeBase elementType = (edmType as RefType).ElementType; MetadataHelper.GetEntitySetAtEnd((AssociationSet)caseMemberPath.Extent, (AssociationEndMember)caseMemberPath.LeafEdmMember); foreach (EdmMember keyMember in elementType.KeyMembers) { int slotIndex = this.GetSlotIndex(caseMemberPath, keyMember); requiredSlots[slotIndex] = true; } } }
// requires: end is given // effects: determine the entity type for an association end member internal static EntityType GetEntityTypeForEnd(AssociationEndMember end) { Debug.Assert(null != end); Debug.Assert(end.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.RefType, "type of association end member must be ref"); RefType refType = (RefType)end.TypeUsage.EdmType; EntityTypeBase endType = refType.ElementType; Debug.Assert(endType.BuiltInTypeKind == BuiltInTypeKind.EntityType, "type of association end reference element must be entity type"); return((EntityType)endType); }
internal DbRelatedEntityRef(RelationshipEndMember sourceEnd, RelationshipEndMember targetEnd, DbExpression targetEntityRef) { // Validate that the specified relationship ends are: // 1. Non-null // 2. From the same metadata workspace as that used by the command tree EntityUtil.CheckArgumentNull(sourceEnd, "sourceEnd"); EntityUtil.CheckArgumentNull(targetEnd, "targetEnd"); // Validate that the specified target entity ref is: // 1. Non-null EntityUtil.CheckArgumentNull(targetEntityRef, "targetEntityRef"); // Validate that the specified source and target ends are: // 1. Declared by the same relationship type if (!object.ReferenceEquals(sourceEnd.DeclaringType, targetEnd.DeclaringType)) { throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_RelatedEntityRef_TargetEndFromDifferentRelationship, "targetEnd"); } // 2. Not the same end if (object.ReferenceEquals(sourceEnd, targetEnd)) { throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_RelatedEntityRef_TargetEndSameAsSourceEnd, "targetEnd"); } // Validate that the specified target end has multiplicity of at most one if (targetEnd.RelationshipMultiplicity != RelationshipMultiplicity.One && targetEnd.RelationshipMultiplicity != RelationshipMultiplicity.ZeroOrOne) { throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_RelatedEntityRef_TargetEndMustBeAtMostOne, "targetEnd"); } // Validate that the specified target entity ref actually has a ref result type if (!TypeSemantics.IsReferenceType(targetEntityRef.ResultType)) { throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_RelatedEntityRef_TargetEntityNotRef, "targetEntityRef"); } // Validate that the specified target entity is of a type that can be reached by navigating to the specified relationship end EntityTypeBase endType = TypeHelpers.GetEdmType <RefType>(targetEnd.TypeUsage).ElementType; EntityTypeBase targetType = TypeHelpers.GetEdmType <RefType>(targetEntityRef.ResultType).ElementType; // if (!endType.EdmEquals(targetType) && !TypeSemantics.IsSubTypeOf(targetType, endType)) { throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_RelatedEntityRef_TargetEntityNotCompatible, "targetEntityRef"); } // Validation succeeded, initialize state _targetEntityRef = targetEntityRef; _targetEnd = targetEnd; _sourceEnd = sourceEnd; }
internal IEnumerable <PropertyRef> GetKeyPropertyRefs() { EntityTypeBase entityType = (EntityTypeBase)null; RefType refType = (RefType)null; entityType = !TypeHelpers.TryGetEdmType <RefType>(this.m_type, out refType) ? TypeHelpers.GetEdmType <EntityTypeBase>(this.m_type) : refType.ElementType; foreach (EdmMember keyMember in entityType.KeyMembers) { System.Data.Entity.Core.Query.PlanCompiler.PlanCompiler.Assert(keyMember is EdmProperty, "Non-EdmProperty key members are not supported"); SimplePropertyRef spr = new SimplePropertyRef(keyMember); yield return((PropertyRef)spr); } }
/// <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 (RelProperty p in relProperties) { yield return(p); } } yield break; }
/// <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 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, this.m_edmCollection, true) .SelectMany(e => ((EntityType)e).Properties) .Where(p => entitySet.ForeignKeyDependents.SelectMany(fk => fk.Item2.ToProperties).Contains(p))); } }
/// <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) { EntityUtil.GenericCheckArgumentNull(entityType, "entityType"); EntityUtil.CheckStringArgument(name, "name"); // SQLBU 480236: 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; }