/// <summary> /// Constructor taking a metadata context, an structural type, and a parent custom type descriptor /// </summary> /// <param name="typeDescriptionContext">The <see cref="LinqToEntitiesTypeDescriptionContext"/> context.</param> /// <param name="edmType">The <see cref="StructuralType"/> type (can be an entity or complex type).</param> /// <param name="parent">The parent custom type descriptor.</param> public LinqToEntitiesTypeDescriptor(LinqToEntitiesTypeDescriptionContext typeDescriptionContext, StructuralType edmType, ICustomTypeDescriptor parent) : base(parent) { this._typeDescriptionContext = typeDescriptionContext; this._edmType = edmType; EdmMember[] timestampMembers = this._edmType.Members.Where(p => ObjectContextUtilities.IsConcurrencyTimestamp(p)).ToArray(); if (timestampMembers.Length == 1) { this._timestampMember = timestampMembers[0]; } if (edmType.BuiltInTypeKind == BuiltInTypeKind.EntityType) { // if any FK member of any association is also part of the primary key, then the key cannot be marked // Editable(false) EntityType entityType = (EntityType)edmType; this._foreignKeyMembers = new HashSet<EdmMember>(entityType.NavigationProperties.SelectMany(p => p.GetDependentProperties())); foreach (EdmProperty foreignKeyMember in this._foreignKeyMembers) { if (entityType.KeyMembers.Contains(foreignKeyMember)) { this._keyIsEditable = true; break; } } } }
/// <summary> /// Creates a new encapsulation of the specified EdmMember. /// </summary> /// <param name="edmMember">Member being encapsulated.</param> internal ObjectContextMember(EdmMember edmMember) { Debug.Assert(edmMember != null, "Can't create ObjectContextMember from a null edmMember."); this.edmMember = edmMember; }
// <summary> // Constrcut a new member mapping metadata object // </summary> protected ObjectMemberMapping(EdmMember edmMember, EdmMember clrMember) { Debug.Assert(edmMember.BuiltInTypeKind == clrMember.BuiltInTypeKind, "BuiltInTypeKind must be the same"); m_edmMember = edmMember; m_clrMember = clrMember; }
public virtual IList <EntityBag> MergeEntities(IEnumerable <EntityBag> entities, out IEnumerable <EntityBag> unmappedEntities) { if (entities == null) { throw new ArgumentNullException(nameof(entities)); } var unmappeds = new List <EntityBag>(); var entityList = entities as IList <EntityBag> ?? entities.ToList(); var mergeList = new Dictionary <ObjectStateEntry, EntityBag>(); foreach (var entityBag in entityList) { var entity = entityBag.Entity; var entityType = EntityTypes.FirstOrDefault(et => et.Name == entity.GetType().Name); EntitySetBase set = null; if (entityType != null) { set = FindEntitySet(entityType); } if (set == null) { unmappeds.Add(entityBag); continue; } var state = entityBag.EntityState; // attach entity to entity set _objectContext.AddObject(set.Name, entity); var entry = _objectContext.ObjectStateManager.GetObjectStateEntry(entity); entry.ChangeState(EFEntityState.Unchanged); mergeList.Add(entry, entityBag); // set original values for modified entities if (state != EntityState.Modified) { continue; } var originalValues = entry.GetUpdatableOriginalValues(); foreach (var originalValue in entityBag.OriginalValues) { var propertyPaths = originalValue.Key.Split('.'); var loopOriginalValues = originalValues; StructuralType loopType = entityType; EdmMember property = null; string lastPropertyName; if (propertyPaths.Length > 1) { for (var i = 0; i < propertyPaths.Length - 1; i++) { var propertyName = propertyPaths[i]; property = loopType.Members.FirstOrDefault(p => p.Name == propertyName); if (property == null) { break; } var ordinal = loopOriginalValues.GetOrdinal(propertyName); loopOriginalValues = (OriginalValueRecord)loopOriginalValues.GetValue(ordinal); loopType = (StructuralType)property.TypeUsage.EdmType; } if (property == null) { continue; } lastPropertyName = propertyPaths[propertyPaths.Length - 1]; } else { lastPropertyName = originalValue.Key; } property = loopType.Members.FirstOrDefault(p => p.Name == lastPropertyName); if (property == null) { continue; } // if modified property is a ComplexType then set all properties of ComplexType to modified. if (property.TypeUsage.EdmType is ComplexType complexType) { PopulateComplexType(loopOriginalValues, property.Name, originalValue.Value, complexType); } else { var ordinal = loopOriginalValues.GetOrdinal(property.Name); loopOriginalValues.SetValue(ordinal, originalValue.Value); } } } foreach (var merge in mergeList) { // and fix the entity state, and relations will also be fixed. if (merge.Value.EntityState == EntityState.Modified) { if (merge.Key.State != EFEntityState.Modified && merge.Value.ForceUpdate) { merge.Key.ChangeState(EFEntityState.Modified); } } else { merge.Key.ChangeState((EFEntityState)merge.Value.EntityState); } } unmappedEntities = unmappeds; return(mergeList.Select(m => m.Value).ToList()); }
// <summary> // Returns a placeholder for a specific metadata member. // </summary> // <param name="member"> EdmMember for which to produce a placeholder. </param> // <returns> Placeholder element for the given member. </returns> private PropagatorResult CreateMemberPlaceholder(EdmMember member) { DebugCheck.NotNull(member); return(Visit(member)); }
public static PropertyInfo GetClrPropertyInfo(this EdmMember property) { DebugCheck.NotNull(property); return(property.Annotations.GetClrPropertyInfo()); }
// used for inserts or updates where the column is not qualified public PropertyExpression(EdmMember property) { _property = property; }
/// <summary> /// Determines if the specified EdmMember is a concurrency timestamp. /// </summary> /// <remarks>Since EF doesn't expose "timestamp" as a first class /// concept, we use the below criteria to infer this for ourselves. /// </remarks> /// <param name="member">The member to check.</param> /// <returns>True or false.</returns> public static bool IsConcurrencyTimestamp(EdmMember member) { Facet facet = member.TypeUsage.Facets.SingleOrDefault(p => p.Name == "ConcurrencyMode"); if (facet == null || facet.Value == null || (ConcurrencyMode)facet.Value != ConcurrencyMode.Fixed) { return false; } facet = member.TypeUsage.Facets.SingleOrDefault(p => p.Name == "FixedLength"); if (facet == null || facet.Value == null || !((bool)facet.Value)) { return false; } facet = member.TypeUsage.Facets.SingleOrDefault(p => p.Name == "MaxLength"); if (facet == null || facet.Value == null || (int)facet.Value != 8) { return false; } MetadataProperty md = ObjectContextUtilities.GetStoreGeneratedPattern(member); if (md == null || facet.Value == null || (string)md.Value != "Computed") { return false; } return true; }
/// <summary> /// Returns true iff member's is a simple non-structures scalar such as primitive or enum. /// </summary> internal static bool IsNonRefSimpleMember(EdmMember member) { return(member.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType || member.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.EnumType); }
// used for inserts or updates where the column is not qualified public PropertyExpression(EdmMember property) { _property = property; }
protected ObjectMemberMapping(EdmMember edmMember, EdmMember clrMember) { this.m_edmMember = edmMember; this.m_clrMember = clrMember; }
/// <summary> /// /// </summary> /// <param name="entityMap"></param> /// <param name="edmProperty"></param> /// <param name="i"></param> /// <param name="prefix"></param> private void MapProperty(EntityMap entityMap, EdmProperty edmProperty, ref int i, ref string prefix) { var identity = entityMap.EdmType.FullName; var entityMembers = TphData[identity].Properties; var columnName = edmProperty.Name; if (entityMembers.Length <= i) { return; } EdmMember edmMember = entityMembers[i]; // check if is complex type if (string.IsNullOrEmpty(prefix) && edmMember.TypeUsage.EdmType.GetType() == typeof(ComplexType)) { prefix = edmMember.Name; ++i; } string propName; if (prefix != null) { if (columnName.StartsWith(prefix + "_")) { propName = columnName.Replace('_', '.'); } else { prefix = null; propName = edmMember.Name; ++i; } } else { propName = entityMembers[i++].Name; } var propInfo = entityMap.Type.GetProperty(propName, '.'); if (propInfo == null) { // entity does not contain such property return; } PropertyMap propertyMap; try { /* * var mi = SqlProviderServices.Instance.GetType().GetMethod("GetSqlDbType", BindingFlags.NonPublic | BindingFlags.Static); * var parameterInfos = mi.GetParameters(); * * var parameters = new List<object>(); * parameters.Add(edmProperty.TypeUsage); * parameters.Add(false); * parameters.Add(SqlVersion); * parameters.Add(null); * parameters.Add(null); * parameters.Add(null); * parameters.Add(null); * * SqlDbType sqlDbType = (SqlDbType) mi.Invoke(null, parameters.ToArray()); */ propertyMap = entityMap.MapProperty(propName, columnName); propertyMap.EdmProperty = edmProperty; propertyMap.EdmMember = edmMember; propertyMap.IsNavigationProperty = edmMember is NavigationProperty; propertyMap.IsFk = propertyMap.IsNavigationProperty || _fks.ContainsKey(edmMember); if (propertyMap.IsFk && _fks.ContainsKey(edmMember)) { propertyMap.FkTargetEdmMember = _fks[edmMember]; entityMap.AddFk(propertyMap); } } catch (Exception ex) { var errorMessage = string.Format("Failed to map propName {0} to column {1} on table {2} ({3})", propName, columnName, entityMap.TableName, entityMap.TypeFullName); throw new Exception(errorMessage, ex); } if (_pks[entityMap.TableName].Contains(columnName)) { propertyMap.IsPk = true; entityMap.AddPk(propertyMap); } foreach (var facet in edmProperty.TypeUsage.Facets) { //System.Data.Entity.Core.Common.DbProviderManifest.ScaleFacetName switch (facet.Name) { case "SRID": try { propertyMap.SRID = (int?)facet.Value; } catch { // nothing to do } break; case "IsStrict": propertyMap.IsStrict = facet.Value != null && (bool)facet.Value; break; case "Unicode": propertyMap.Unicode = facet.Value != null && (bool)facet.Value; break; case "FixedLength": propertyMap.FixedLength = facet.Value != null && (bool)facet.Value; break; case "Precision": propertyMap.Precision = (byte)facet.Value; break; case "Scale": propertyMap.Scale = (byte)facet.Value; break; case "Nullable": propertyMap.IsRequired = !(bool)facet.Value; break; case "DefaultValue": propertyMap.DefaultValue = facet.Value; break; case "StoreGeneratedPattern": propertyMap.IsIdentity = (StoreGeneratedPattern)facet.Value == StoreGeneratedPattern.Identity; propertyMap.Computed = (StoreGeneratedPattern)facet.Value == StoreGeneratedPattern.Computed; break; case "MaxLength": if (facet.Value == null) { propertyMap.MaxLength = int.MaxValue; } else { int result; var val = facet.Value.ToString(); if (!Int32.TryParse(val, out result)) { if (val == "Max") { propertyMap.MaxLength = int.MaxValue; } } propertyMap.MaxLength = result; } break; } } }
internal PropagatorResult GetMemberValue(EdmMember member) { return(this.GetMemberValue(TypeHelpers.GetAllStructuralMembers((EdmType)this.StructuralType).IndexOf(member))); }
public static void SetClrPropertyInfo(this EdmMember property, PropertyInfo propertyInfo) { DebugCheck.NotNull(property); property.Annotations.SetClrPropertyInfo(propertyInfo); }
/// <summary> /// This method attempts to determine if the specified table has an integer /// primary key (i.e. "rowid"). If so, it sets the /// <paramref name="primaryKeyMember" /> parameter to the right /// <see cref="EdmMember" />; otherwise, the /// <paramref name="primaryKeyMember" /> parameter is set to null. /// </summary> /// <param name="table">The table to check.</param> /// <param name="keyMembers"> /// The collection of key members. An attempt is always made to set this /// parameter to a valid value. /// </param> /// <param name="primaryKeyMember"> /// The <see cref="EdmMember" /> that represents the integer primary key /// -OR- null if no such <see cref="EdmMember" /> exists. /// </param> /// <returns> /// Non-zero if the specified table has an integer primary key. /// </returns> private static bool IsIntegerPrimaryKey( EntitySetBase table, out ReadOnlyMetadataCollection<EdmMember> keyMembers, out EdmMember primaryKeyMember ) { keyMembers = table.ElementType.KeyMembers; if (keyMembers.Count == 1) /* NOTE: The "rowid" only? */ { EdmMember keyMember = keyMembers[0]; PrimitiveTypeKind typeKind; if (MetadataHelpers.TryGetPrimitiveTypeKind( keyMember.TypeUsage, out typeKind) && (typeKind == PrimitiveTypeKind.Int64)) { primaryKeyMember = keyMember; return true; } } primaryKeyMember = null; return false; }
// Determines whether the given member is declared as a concurrency property internal static ConcurrencyMode GetConcurrencyMode(EdmMember member) { return(GetConcurrencyMode(member.TypeUsage)); }
internal void ValidateEntityKey( MetadataWorkspace workspace, EntitySet entitySet, bool isArgumentException, string argumentName) { if (entitySet == null) { return; } ReadOnlyMetadataCollection <EdmMember> keyMembers = ((EntitySetBase)entitySet).ElementType.KeyMembers; if (this._singletonKeyValue != null) { if (keyMembers.Count != 1) { if (isArgumentException) { throw new ArgumentException(Strings.EntityKey_IncorrectNumberOfKeyValuePairs((object)entitySet.ElementType.FullName, (object)keyMembers.Count, (object)1), argumentName); } throw new InvalidOperationException(Strings.EntityKey_IncorrectNumberOfKeyValuePairs((object)entitySet.ElementType.FullName, (object)keyMembers.Count, (object)1)); } EntityKey.ValidateTypeOfKeyValue(workspace, keyMembers[0], this._singletonKeyValue, isArgumentException, argumentName); if (!(this._keyNames[0] != keyMembers[0].Name)) { return; } if (isArgumentException) { throw new ArgumentException(Strings.EntityKey_MissingKeyValue((object)keyMembers[0].Name, (object)entitySet.ElementType.FullName), argumentName); } throw new InvalidOperationException(Strings.EntityKey_MissingKeyValue((object)keyMembers[0].Name, (object)entitySet.ElementType.FullName)); } if (this._compositeKeyValues == null) { return; } if (keyMembers.Count != this._compositeKeyValues.Length) { if (isArgumentException) { throw new ArgumentException(Strings.EntityKey_IncorrectNumberOfKeyValuePairs((object)entitySet.ElementType.FullName, (object)keyMembers.Count, (object)this._compositeKeyValues.Length), argumentName); } throw new InvalidOperationException(Strings.EntityKey_IncorrectNumberOfKeyValuePairs((object)entitySet.ElementType.FullName, (object)keyMembers.Count, (object)this._compositeKeyValues.Length)); } for (int index1 = 0; index1 < this._compositeKeyValues.Length; ++index1) { EdmMember keyMember = ((EntitySetBase)entitySet).ElementType.KeyMembers[index1]; bool flag = false; for (int index2 = 0; index2 < this._compositeKeyValues.Length; ++index2) { if (keyMember.Name == this._keyNames[index2]) { EntityKey.ValidateTypeOfKeyValue(workspace, keyMember, this._compositeKeyValues[index2], isArgumentException, argumentName); flag = true; break; } } if (!flag) { if (isArgumentException) { throw new ArgumentException(Strings.EntityKey_MissingKeyValue((object)keyMember.Name, (object)entitySet.ElementType.FullName), argumentName); } throw new InvalidOperationException(Strings.EntityKey_MissingKeyValue((object)keyMember.Name, (object)entitySet.ElementType.FullName)); } } }
// Generates T-SQL describing a member // Requires: member must belong to an entity type (a safe requirement for DML // SQL gen, where we only access table columns) private static string GenerateMemberTSql(EdmMember member) { return SqlGenerator.QuoteIdentifier(member.Name); }
/// <summary> /// Returns a collection of all the <see cref="Attribute"/>s we infer from the metadata associated /// with the metadata member corresponding to the given property descriptor /// </summary> /// <param name="pd">A <see cref="PropertyDescriptor"/> to examine</param> /// <returns>A collection of attributes inferred from the metadata in the given descriptor.</returns> protected override IEnumerable <Attribute> GetMemberAttributes(PropertyDescriptor pd) { List <Attribute> attributes = new List <Attribute>(); // Exclude any EntityState, EntityReference, etc. members if (ShouldExcludeEntityMember(pd)) { // for these members, we don't want to do any further // attribute inference attributes.Add(new ExcludeAttribute()); return(attributes.ToArray()); } EditableAttribute editableAttribute = null; bool inferRoundtripOriginalAttribute = false; bool hasKeyAttribute = (pd.Attributes[typeof(KeyAttribute)] != null); bool isEntity = this.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType; if (isEntity) { EntityType entityType = (EntityType)this.EdmType; EdmMember keyMember = entityType.KeyMembers.SingleOrDefault(k => k.Name == pd.Name); if (keyMember != null && !hasKeyAttribute) { attributes.Add(new KeyAttribute()); hasKeyAttribute = true; } } EdmProperty member = this.EdmType.Members.SingleOrDefault(p => p.Name == pd.Name) as EdmProperty; if (member != null) { if (hasKeyAttribute) { // key members must always be roundtripped inferRoundtripOriginalAttribute = true; // key members that aren't also FK members are non-editable (but allow an initial value) if (!this._keyIsEditable) { editableAttribute = new EditableAttribute(false) { AllowInitialValue = true }; } } // Check if the member is DB generated and add the DatabaseGeneratedAttribute to it if not already present. bool databaseGenerated = false; if (pd.Attributes[typeof(DatabaseGeneratedAttribute)] == null) { MetadataProperty md = ObjectContextUtilities.GetStoreGeneratedPattern(member); if (md != null) { if ((string)md.Value == "Computed") { attributes.Add(new DatabaseGeneratedAttribute(DatabaseGeneratedOption.Computed)); databaseGenerated = true; } else if ((string)md.Value == "Identity") { attributes.Add(new DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)); databaseGenerated = true; } } } else { databaseGenerated = ((DatabaseGeneratedAttribute)pd.Attributes[typeof(DatabaseGeneratedAttribute)]).DatabaseGeneratedOption != DatabaseGeneratedOption.None; } // Add implicit ConcurrencyCheck attribute to metadata if ConcurrencyMode is anything other than ConcurrencyMode.None Facet facet = member.TypeUsage.Facets.SingleOrDefault(p => p.Name == "ConcurrencyMode"); if (facet != null && facet.Value != null && (ConcurrencyMode)facet.Value != ConcurrencyMode.None && pd.Attributes[typeof(ConcurrencyCheckAttribute)] == null) { attributes.Add(new ConcurrencyCheckAttribute()); inferRoundtripOriginalAttribute = true; } // Add Required attribute to metadata if the member cannot be null and it is either a reference type or a Nullable<T> // unless it is a database generated field if (!member.Nullable && (!pd.PropertyType.IsValueType || IsNullableType(pd.PropertyType)) && !databaseGenerated && pd.Attributes[typeof(RequiredAttribute)] == null) { attributes.Add(new RequiredAttribute()); } bool isStringType = pd.PropertyType == typeof(string) || pd.PropertyType == typeof(char[]); if (isStringType && pd.Attributes[typeof(StringLengthAttribute)] == null) { facet = member.TypeUsage.Facets.SingleOrDefault(p => p.Name == "MaxLength"); if (facet != null && facet.Value != null && facet.Value.GetType() == typeof(int)) { // need to test for Type int, since the value can also be of type // System.Data.Metadata.Edm.EdmConstants.Unbounded int maxLength = (int)facet.Value; attributes.Add(new StringLengthAttribute(maxLength)); } } bool hasTimestampAttribute = (pd.Attributes[typeof(TimestampAttribute)] != null); if (this._timestampMember == member && !hasTimestampAttribute) { attributes.Add(new TimestampAttribute()); hasTimestampAttribute = true; } // All members marked with TimestampAttribute (inferred or explicit) need to // have [Editable(false)] and [RoundtripOriginal] applied if (hasTimestampAttribute) { inferRoundtripOriginalAttribute = true; if (editableAttribute == null) { editableAttribute = new EditableAttribute(false); } } // Add RTO to this member if required. If this type has a timestamp // member that member should be the ONLY member we apply RTO to. // Dont apply RTO if it is an association member. bool isForeignKeyMember = this._foreignKeyMembers != null && this._foreignKeyMembers.Contains(member); if ((this._timestampMember == null || this._timestampMember == member) && (inferRoundtripOriginalAttribute || isForeignKeyMember) && pd.Attributes[typeof(AssociationAttribute)] == null) { if (pd.Attributes[typeof(RoundtripOriginalAttribute)] == null) { attributes.Add(new RoundtripOriginalAttribute()); } } } // Add the Editable attribute if required if (editableAttribute != null && pd.Attributes[typeof(EditableAttribute)] == null) { attributes.Add(editableAttribute); } if (isEntity) { this.AddAssociationAttributes(pd, attributes); } return(attributes.ToArray()); }
public PropertyExpression(PropertyExpression expression) { _variable = new VariableReferenceExpression(expression._variable); _property = expression._property; }
protected static MemberAttributes GetSetterAccessibility(EdmMember item) { return(GetAccessibilityValue(item, XmlConstants.SetterAccess)); }
/// <summary> /// Returns nested value. Only valid when <see cref="IsSimple" /> is false. /// </summary> /// <param name="member">Member for which to return a value</param> /// <returns>Nested result.</returns> internal PropagatorResult GetMemberValue(EdmMember member) { int ordinal = TypeHelpers.GetAllStructuralMembers(this.StructuralType).IndexOf(member); return(GetMemberValue(ordinal)); }
// <summary> // Creates a path corresponding to <paramref name="extent" />.<paramref name="member" /> // </summary> internal MemberPath(EntitySetBase extent, EdmMember member) : this(extent, Enumerable.Repeat(member, 1)) { }
public bool CanProxyMember(EdmMember member) { return(_scalarMembers.Contains(member) || _relationshipMembers.Contains(member)); }
// <summary> // Creates a member path corresponding to the path <paramref name="prefix" />.<paramref name="last" /> // </summary> internal MemberPath(MemberPath prefix, EdmMember last) { m_extent = prefix.m_extent; m_path = new List <EdmMember>(prefix.m_path); m_path.Add(last); }
/// <summary> /// More useful default constructor /// </summary> /// <param name="property"> property describing this column </param> internal ColumnMD(EdmMember property) : this(property.Name, property.TypeUsage) { m_property = property; }
/// <summary> /// Returns a placeholder for a specific metadata member. /// </summary> /// <param name="member">EdmMember for which to produce a placeholder.</param> /// <returns>Placeholder element for the given member.</returns> private PropagatorResult CreateMemberPlaceholder(EdmMember member) { EntityUtil.CheckArgumentNull(member, "member"); return(Visit(member)); }
private static void ValidateMembersMatch(EdmMember edmMember, EdmMember objectMember) { Debug.Assert(edmMember.DeclaringType.DataSpace == DataSpace.CSpace, "the cspace member is not on a cspace type"); Debug.Assert(objectMember.DeclaringType.DataSpace == DataSpace.OSpace, "the ospace member is not on a cspace type"); // Make sure the property type is the same if (edmMember.BuiltInTypeKind != objectMember.BuiltInTypeKind) { throw new MappingException( Strings.Mapping_Default_OCMapping_MemberKind_Mismatch( edmMember.Name, edmMember.DeclaringType.FullName, edmMember.BuiltInTypeKind, objectMember.Name, objectMember.DeclaringType.FullName, objectMember.BuiltInTypeKind)); } // Make sure the member type is the same if (edmMember.TypeUsage.EdmType.BuiltInTypeKind != objectMember.TypeUsage.EdmType.BuiltInTypeKind) { throw Error.Mapping_Default_OCMapping_Member_Type_Mismatch( edmMember.TypeUsage.EdmType.Name, edmMember.TypeUsage.EdmType.BuiltInTypeKind, edmMember.Name, edmMember.DeclaringType.FullName, objectMember.TypeUsage.EdmType.Name, objectMember.TypeUsage.EdmType.BuiltInTypeKind, objectMember.Name, objectMember.DeclaringType.FullName); } if (Helper.IsPrimitiveType(edmMember.TypeUsage.EdmType)) { var memberType = Helper.GetSpatialNormalizedPrimitiveType(edmMember.TypeUsage.EdmType); // We expect the CLR prmitive type and their corresponding EDM primitive types to have the same primitive type kind (at least for now) if (memberType.PrimitiveTypeKind != ((PrimitiveType)objectMember.TypeUsage.EdmType).PrimitiveTypeKind) { throw new MappingException( Strings.Mapping_Default_OCMapping_Invalid_MemberType( edmMember.TypeUsage.EdmType.FullName, edmMember.Name, edmMember.DeclaringType.FullName, objectMember.TypeUsage.EdmType.FullName, objectMember.Name, objectMember.DeclaringType.FullName)); } } else if (Helper.IsEnumType(edmMember.TypeUsage.EdmType)) { Debug.Assert( Helper.IsEnumType(objectMember.TypeUsage.EdmType), "Both types are expected to by EnumTypes. For non-matching types we should have already thrown."); ValidateEnumTypeMapping((EnumType)edmMember.TypeUsage.EdmType, (EnumType)objectMember.TypeUsage.EdmType); } else { EdmType edmMemberType; EdmType objectMemberType; if (BuiltInTypeKind.AssociationEndMember == edmMember.BuiltInTypeKind) { edmMemberType = ((RefType)edmMember.TypeUsage.EdmType).ElementType; objectMemberType = ((RefType)objectMember.TypeUsage.EdmType).ElementType; } else if (BuiltInTypeKind.NavigationProperty == edmMember.BuiltInTypeKind && Helper.IsCollectionType(edmMember.TypeUsage.EdmType)) { edmMemberType = ((CollectionType)edmMember.TypeUsage.EdmType).TypeUsage.EdmType; objectMemberType = ((CollectionType)objectMember.TypeUsage.EdmType).TypeUsage.EdmType; } else { edmMemberType = edmMember.TypeUsage.EdmType; objectMemberType = objectMember.TypeUsage.EdmType; } if (edmMemberType.Identity != ObjectItemCollection.TryGetMappingCSpaceTypeIdentity(objectMemberType)) { throw new MappingException( Strings.Mapping_Default_OCMapping_Invalid_MemberType( edmMember.TypeUsage.EdmType.FullName, edmMember.Name, edmMember.DeclaringType.FullName, objectMember.TypeUsage.EdmType.FullName, objectMember.Name, objectMember.DeclaringType.FullName)); } } }
public static bool IsKey(this EdmMember member) { Debug.Assert(member != null, "member is null."); return(((EntityType)member.DeclaringType).KeyMembers.Contains(member)); }
protected virtual void Visit(EdmMember edmMember) { Visit(edmMember.TypeUsage); }
// <summary> // Aligns a value returned from the store with the expected type for the member. // </summary> // <param name="value"> Value to convert. </param> // <param name="member"> Metadata for the member being set. </param> // <returns> Converted return value </returns> internal object AlignReturnValue(object value, EdmMember member) { if (DBNull.Value.Equals(value)) { // check if there is a nullability constraint on the value if (BuiltInTypeKind.EdmProperty == member.BuiltInTypeKind && !((EdmProperty)member).Nullable) { throw EntityUtil.Update( Strings.Update_NullReturnValueForNonNullableMember( member.Name, member.DeclaringType.FullName), null); } } else if (!Helper.IsSpatialType(member.TypeUsage)) { Type clrType; Type clrEnumType = null; if (Helper.IsEnumType(member.TypeUsage.EdmType)) { var underlyingType = Helper.AsPrimitive(member.TypeUsage.EdmType); clrEnumType = Record.GetFieldType(RecordOrdinal); clrType = underlyingType.ClrEquivalentType; Debug.Assert(clrEnumType.IsEnum()); } else { // convert the value to the appropriate CLR type Debug.Assert( BuiltInTypeKind.PrimitiveType == member.TypeUsage.EdmType.BuiltInTypeKind, "we only allow return values that are instances of EDM primitive or enum types"); var primitiveType = (PrimitiveType)member.TypeUsage.EdmType; clrType = primitiveType.ClrEquivalentType; } try { value = Convert.ChangeType(value, clrType, CultureInfo.InvariantCulture); if (clrEnumType != null) { value = Enum.ToObject(clrEnumType, value); } } catch (Exception e) { // we should not be wrapping all exceptions if (e.RequiresContext()) { var userClrType = clrEnumType ?? clrType; throw EntityUtil.Update( Strings.Update_ReturnValueHasUnexpectedType( value.GetType().FullName, userClrType.FullName, member.Name, member.DeclaringType.FullName), e); } throw; } } // return the adjusted value return(value); }
/// <summary> /// This method attempts to determine if all the specified key members have /// values available. /// </summary> /// <param name="translator"> /// The <see cref="ExpressionTranslator" /> to use. /// </param> /// <param name="keyMembers"> /// The collection of key members to check. /// </param> /// <param name="missingKeyMember"> /// The first missing key member that is found. This is only set to a valid /// value if the method is returning false. /// </param> /// <returns> /// Non-zero if all key members have values; otherwise, zero. /// </returns> private static bool DoAllKeyMembersHaveValues( ExpressionTranslator translator, ReadOnlyMetadataCollection<EdmMember> keyMembers, out EdmMember missingKeyMember ) { foreach (EdmMember keyMember in keyMembers) { if (!translator.MemberValues.ContainsKey(keyMember)) { missingKeyMember = keyMember; return false; } } missingKeyMember = null; return true; }
public PropertyExpression(VariableReferenceExpression variable, EdmMember property) { _variable = variable; _property = property; }
// Generates SQL describing a member // Requires: member must belong to an entity type (a safe requirement for DML // SQL gen, where we only access table columns) internal static string GenerateMemberSql(EdmMember member) { return SqlGenerator.QuoteIdentifier(member.Name); }
public PropertyExpression(PropertyExpression expression) { _variable = new VariableReferenceExpression(expression._variable); _property = expression._property; }
/// <summary> /// Gets the <see cref="StoreGeneratedPattern"/> property value from the edm member. /// </summary> /// <param name="member">The EdmMember from which to get the StoreGeneratedPattern value.</param> /// <returns>The <see cref="StoreGeneratedPattern"/> value.</returns> public static MetadataProperty GetStoreGeneratedPattern(EdmMember member) { MetadataProperty md; member.MetadataProperties.TryGetValue("http://schemas.microsoft.com/ado/2009/02/edm/annotation:StoreGeneratedPattern", /* ignoreCase */ true, out md); return md; }
// used for inserts or updates where the column is not qualified public PropertyExpression(EdmMember property) { _variable = null; _property = property; }
private static Type ExtractExpectedTypeForCoercion(EdmMember member) { var type = ((PrimitiveType)member.TypeUsage.EdmType).ClrEquivalentType; return MakeTypeCoercion(type, member.TypeUsage); }
private static Type ExtractExpectedTypeForCoercion(EdmMember member) { var type = ((PrimitiveType)member.TypeUsage.EdmType).ClrEquivalentType; return(MakeTypeCoercion(type, member.TypeUsage)); }
public PropertyExpression(VariableReferenceExpression variable, EdmMember property) { _variable = variable; _property = property; }
// Generates T-SQL describing a member // Requires: member must belong to an entity type (a safe requirement for DML // SQL gen, where we only access table columns) private static string GenerateMemberTSql(EdmMember member) { return(SqlGenerator.QuoteIdentifier(member.Name)); }
// used for inserts or updates where the column is not qualified public PropertyExpression(EdmMember property) { _variable = null; _property = property; }
/// <summary> /// Creates a new encapsulation of the specified EdmMember. /// </summary> /// <param name="edmMember">Member being encapsulated.</param> internal ObjectContextMember(EdmMember edmMember) { Debug.Assert(edmMember != null, "Can't create ObjectContextMember from a null edmMember."); this.edmMember = edmMember; }