Improve navigation property names when reverse engineering a database

Entity FrameworkEf Code-FirstT4Entity Framework-5Ef Power-Tools

Entity Framework Problem Overview


I'm using Entity Framework 5 with Visual Studio with Entity Framework Power Tools Beta 2 to reverse engineer moderately sized databases (~100 tables).

Unfortunately, the navigation properties do not have meaningful names. For example, if there are two tables:

CREATE TABLE Contacts (
    ContactID INT IDENTITY (1, 1) NOT NULL,
    ...
    CONSTRAINT PK_Contacts PRIMARY KEY CLUSTERED (ContactID ASC)
}

CREATE TABLE Projects (
    ProjectID INT IDENTITY (1, 1) NOT NULL,
    TechnicalContactID INT NOT NULL,
    SalesContactID INT NOT NULL,
    ...
    CONSTRAINT PK_Projects PRIMARY KEY CLUSTERED (ProjectID ASC),
    CONSTRAINT FK_Projects_TechnicalContact FOREIGN KEY (TechnicalContactID)
        REFERENCES Contacts (ContactID),
    CONSTRAINT FK_Projects_SalesContact FOREIGN KEY (SalesContactID)
        REFERENCES Contacts (ContactID),
    ...
}

This will generate classes like this:

public class Contact
{
     public Contact()
     {
          this.Projects = new List<Project>();
          this.Projects1 = new List<Project>();
     }
     public int ContactID { get; set; }
     // ...
     public virtual ICollection<Project> Projects { get; set; }
     public virtual ICollection<Project> Projects1 { get; set; }
}

public class Project
{
     public Project()
     {

     }
     public int ProjectID { get; set; }
     public int TechnicalContactID { get; set; }
     public int SalesContactID { get; set; }
     // ...
     public virtual Contact Contact { get; set; }
     public virtual Contact Contact1 { get; set; }
}

I see several variants which would all be better than this:

  • Use the name of the foreign key: For example, everything after the last underscore (FK_Projects_TechnicalContact --> TechnicalContact). Though this probably would be the solution with the most control, this may be more difficult to integrate with the existing templates.
  • Use the property name corresponding to the foreign key column: Strip off the suffix ID (TechnicalContactID --> TechnicalContact)
  • Use the concatenation of property name and the existing solution: Example TechnicalContactIDProjects (collection) and TechnicalContactIDContact

Luckily, it is possible to modify the templates by including them in the project.

The modifications would have to be made to Entity.tt and Mapping.tt. I find it difficult due to the lack of intellisense and debug possibilities to make those changes.


Concatenating property names (third in above list) is probably the easiest solution to implement.

How to change the creation of navigational properties in Entity.tt and Mapping.tt to achieve the following result:

public class Contact
{
     public Contact()
     {
          this.TechnicalContactIDProjects = new List<Project>();
          this.SalesContactIDProjects = new List<Project>();
     }
     public int ContactID { get; set; }
     // ...
     public virtual ICollection<Project> TechnicalContactIDProjects { get; set; }
     public virtual ICollection<Project> SalesContactIDProjects { get; set; }
}

public class Project
{
     public Project()
     {

     }
     public int ProjectID { get; set; }
     public int TechnicalContactID { get; set; }
     public int SalesContactID { get; set; }
     // ...
     public virtual Contact TechnicalContactIDContact { get; set; }
     public virtual Contact SalesContactIDContact { get; set; }
}

Entity Framework Solutions


Solution 1 - Entity Framework

There a few things you need to change inside the .tt file. I choose to use the third solution you suggested but this requires to be formatted like FK_CollectionName_RelationName. I split them up with '_' and use the last string in the array. I use the RelationName with the ToEndMember property to create a property name. FK_Projects_TechnicalContact will result in

//Plularized because of EF. 
public virtual Contacts TechnicalContactContacts { get; set; }

and your projects will be like this.

public virtual ICollection<Projects> SalesContactProjects { get;  set; }
public virtual ICollection<Projects> TechnicalContactProjects { get;  set; }

Now the code you may ask. Ive added 2 functions to the CodeStringGenerator class in the T4 file. One which builds the propertyName recieving a NavigationProperty. and the other one generating the code for the property recieving a NavigationProperty and the name for the property.

//CodeStringGenerator class
public string GetPropertyNameForNavigationProperty(NavigationProperty navigationProperty)
{
	var ForeignKeyName = navigationProperty.RelationshipType.Name.Split('_');
	var propertyName = ForeignKeyName[ForeignKeyName.Length-1] + navigationProperty.ToEndMember.Name;
	return propertyName;
}

public string NavigationProperty(NavigationProperty navigationProperty, string name)
{
    var endType = _typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType());
    return string.Format(
        CultureInfo.InvariantCulture,
        "{0} {1} {2} {{ {3}get; {4}set; }}",
        AccessibilityAndVirtual(Accessibility.ForProperty(navigationProperty)),
        navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType,
        name,
        _code.SpaceAfter(Accessibility.ForGetter(navigationProperty)),
        _code.SpaceAfter(Accessibility.ForSetter(navigationProperty)));
}

If you place the above code in the class you still need to change 2 parts. You need to find the place where the constructor part and the navigation property part are being build up of the entity. In the constructor part (around line 60) you need to replace the existing code by calling the method GetPropertyNameForNavigationProperty and passing this into the escape method.

      var propName = codeStringGenerator.GetPropertyNameForNavigationProperty(navigationProperty);
#>
      this.<#=code.Escape(propName)#> = new HashSet<<#=typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType())#>>();
<#

And in the NavigationProperties part (around line 100) you also need to replace the code with the following.

	var propName = codeStringGenerator.GetPropertyNameForNavigationProperty(navigationProperty);
#>
    <#=codeStringGenerator.NavigationProperty(navigationProperty, propName)#>
<#

I hope this helps and you can always debug the GetPropertyNameForNavigationProperty function and play a little with the naming of the property.

Solution 2 - Entity Framework

Building on BikeMrown's answer, we can add Intellisense to the properties using the RelationshipName that is set in MSSQL:

MSSQL relationships

Edit model.tt in your VS Project, and change this:

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
<#
            }
#>
    <#=codeStringGenerator.NavigationProperty(navigationProperty)#>
<#
        }
    }

to this:

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
<#
            }
#>
    /// <summary>
    /// RelationshipName: <#=code.Escape(navigationProperty.RelationshipType.Name)#>
    /// </summary>
    <#=codeStringGenerator.NavigationProperty(navigationProperty)#>
<#
        }
    }

Now when you start typing a property name, you get a tooltip like this: Intellisense tooltip

It's probably worth noting that if you change your DB model, the properties may find themselves pointing at different DB fields because the EF generates navigation property names based on their respective DB field name's alphabetic precedence!

Solution 3 - Entity Framework

Found this question/answer very helpful. However, I didn't want to do as much as Rikko's answer. I just needed to find the column name involved in the NavigationProperty and wasn't seeing how to get that in any of the samples (at least not without an edmx to pull from).

<#
  var association = (AssociationType)navProperty.RelationshipType;
#>	//	<#= association.ReferentialConstraints.Single().ToProperties.Single().Name #>

Solution 4 - Entity Framework

The selected answer is awesome and got me going in the right direction for sure. But my big problem with it is that it took all of my already working navigation properties and appended the base type name to them, so you'd end up with with things like the following.

public virtual Need UnitNeed { get; set;}
public virtual ShiftEntered UnitShiftEntered {get; set;}`

So I dug into the proposed additions to the .tt file and modified them a bit to remove duplicate type naming and clean things up a bit. I figure there's gotta be someone else out there that would want the same thing so I figured I'd post my resolution here.

Here's the code to update within the public class CodeStringGenerator

public string GetPropertyNameForNavigationProperty(NavigationProperty navigationProperty, string entityname = "")
{
	var ForeignKeyName = navigationProperty.RelationshipType.Name.Split('_');
	var propertyName = "";
	
	if (ForeignKeyName[ForeignKeyName.Length-1] != entityname){
		var prepender = (ForeignKeyName[ForeignKeyName.Length-1].EndsWith(entityname)) ? ReplaceLastOccurrence(ForeignKeyName[ForeignKeyName.Length-1], entityname, "") :  ForeignKeyName[ForeignKeyName.Length-1];
		propertyName = prepender + navigationProperty.ToEndMember.Name;
	}
	else {
		propertyName = navigationProperty.ToEndMember.Name;
	}

	return propertyName;
}

public string NavigationProperty(NavigationProperty navigationProperty, string name)
{
	var endType = _typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType());

	var truname = name;
		
	if(navigationProperty.ToEndMember.RelationshipMultiplicity != RelationshipMultiplicity.Many){
		if(name.Split(endType.ToArray<char>()).Length > 1){
			truname = ReplaceLastOccurrence(name, endType, "");
		}
	}

	return string.Format(
		CultureInfo.InvariantCulture,
		"{0} {1} {2} {{ {3}get; {4}set; }}",
		AccessibilityAndVirtual(Accessibility.ForProperty(navigationProperty)),
		navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType,
		truname,
		_code.SpaceAfter(Accessibility.ForGetter(navigationProperty)),
		_code.SpaceAfter(Accessibility.ForSetter(navigationProperty)));
}

public static string ReplaceLastOccurrence(string Source, string Find, string Replace)
{
		int place = Source.LastIndexOf(Find);

		if(place == -1)
		   return Source;

		string result = Source.Remove(place, Find.Length).Insert(place, Replace);
		return result;
}

and here's the code to update within the model generation,

update both occurrences of this:

var propName = codeStringGenerator.GetPropertyNameForNavigationProperty(navigationProperty)

to this

var propName = codeStringGenerator.GetPropertyNameForNavigationProperty(navigationProperty, entity.Name);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarapetView Question on Stackoverflow
Solution 1 - Entity FrameworkRik van den BergView Answer on Stackoverflow
Solution 2 - Entity Framework3-14159265358979323846264View Answer on Stackoverflow
Solution 3 - Entity FrameworkBikeMrownView Answer on Stackoverflow
Solution 4 - Entity FrameworkDylan HayesView Answer on Stackoverflow