internal static IEnumerable <string> GetDependentPropertyNames(NavigationProperty navigationProperty, bool checkRelationshipType) { if (checkRelationshipType) { if (navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.ZeroOrOne && navigationProperty.FromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One) { // Get constraint when this association is on the "parent" (aka "from") side. This means // that the navProperty represents a Children association in a 1-1 relationship. For example, // this could be a Item-ItemDetail scenario where the ItemDetail table has a PK that is also an FK // into the Item table (thus ensuring the 1-1 cardinality). We need to special case this situation because normally we would try // to build a foreign key name of the form "Item.ItemID", but we want just "ItemID". AssociationType relationshipType = (AssociationType)navigationProperty.RelationshipType; ReferentialConstraint constraint = relationshipType.ReferentialConstraints.FirstOrDefault(c => c.ToRole == navigationProperty.ToEndMember); if (constraint != null) { return(constraint.FromProperties.Select(p => p.Name)); } // Fall back on the primary keys if no constraints were found but only if we are on the parent side. i.e the 1 side Item side in an Item-ItemDetail // Get the primary keys on the "from" side of the relationship. i.e Product.Category -> ProductID return(navigationProperty.FromEndMember.GetEntityType().KeyMembers.Select(m => m.Name)); } } return(navigationProperty.GetDependentProperties().Select(m => m.Name)); }
private static IPropertyConstraint GetForeignKeyConstraint(NavigationProperty navProp) { if (navProp.GetDependentProperties().Count() != 1 || navProp.ToEndMember.GetEntityType().KeyProperties.Count != 1) { return(null); } var dependencyProp = navProp.GetDependentProperties().Single(); var keyProp = navProp.ToEndMember.GetEntityType().KeyProperties.Single(); var fromType = navProp.FromEndMember.GetEntityType().GetClrType(); var toType = navProp.ToEndMember.GetEntityType().GetClrType(); var navPropInfo = navProp.GetProperty(); var foreignKeyPropInfo = fromType.GetProperty(dependencyProp); var keyPropInfo = toType.GetProperty(keyProp); var keyType = keyPropInfo.PropertyType; var type = typeof(ForeignKeyConstraint <, ,>) .MakeGenericType(fromType, toType, keyType); return((IPropertyConstraint)Activator.CreateInstance(type, navPropInfo, foreignKeyPropInfo, keyPropInfo)); }