I have created an edmx file with a database first approach and have adapted a navigation property name from User.Contact1
to User.DefaultContact
in the T4 template like below
string foreignKeyName = navigationProperty.RelationshipType.Name;
string customizedPropertyName = customizedPropertyNames
.Where(x => x.EntityName == entity.Name && foreignKeyName == x.ForeignKeyName)
.FirstOrDefault()?.PropertyName;
string propertyDefinition = codeStringGenerator.NavigationProperty(navigationProperty, customizedPropertyName);
The name is changed successfully but it causes a runtime MetadataException
System.Data.Entity.Core.MetadataException : Schema specified is not valid. Errors:
The relationship 'Model.FK_User_Contact' was not loaded because the type 'User' is not available.
The following information may be useful in resolving the previous error:
The required property 'Contact1' does not exist on the type 'User'.
Then when I also changed the navigation property name in edmx manually, the error went away.
<EntityType Name="User">
<NavigationProperty Name="DefaultContact" Relationship="Self.FK_User_DefaultContact" FromRole="User" ToRole="Contact" />
</EntityType>
My questions are
Why is edmx file affecting the runtime behavior(fixed the exception)? Shouldn't it be just a design time tool? After the edmx modification, I re-run all the T4 templates. It causes no change in all the generated C# code(verified in git)
What is the root cause of the error. Is there anyway to fix this with just T4 template adaptation, without manual editing of edmx file?
Update:
My assumption that edmx is only for design time is wrong. It is also compiled into 3 embedded resource files (.csdl, .msl, .ssdl). The navigation property name is defined also in the .csdl file. Adapting the T4 template will create C# model class that does not match the csdl file, this is what's causing the MetadataException.
Then the question is, how come there are so many Stackoverflow answers suggesting adapting T4 template is the way to go to generate customized navigation property names?