3

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

  1. 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)

  2. 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?

Xiaoguo Ge
  • 2,177
  • 20
  • 26
  • You can modify the T4 template to change the output. For example if you want to derive from a custom class, for additional functionality. Just remember you could just as easily (better to) rename properties in the EDMX designer surface because the template **is** reading the edmx to generate its output. – reckface Sep 19 '17 at 07:48

0 Answers0