问题
I have the following table:
CREATE TABLE Phone(
PhoneId INT IDENTITY (1, 1) NOT NULL,
CONSTRAINT PK_Phone PRIMARY KEY CLUSTERED (PhoneId ASC))
CREATE TABLE Person(
PersonId INT IDENTITY (1, 1) NOT NULL,
MobilePhoneId INT NOT NULL,
PhoneId INT NOT NULL,
...
CONSTRAINT PK_Person PRIMARY KEY CLUSTERED (PersonId ASC),
CONSTRAINT FK_Projects_Phone FOREIGN KEY (PhoneId)
REFERENCES Phone(PhoneId),
CONSTRAINT FK_Projects_MobileId FOREIGN KEY (MobilePhoneId)
REFERENCES Phone(PhoneId),
...
I am using EF an I would like to generate navigation properties based on the foreign keys, removing the Id part, so I would like to have navigation properties Phone and MobilePhone. I tried to debug, but I did not find where are the foreign keys stored.Please help with the TT template: where and what shoult I modify.
回答1:
You can do it by edit edmx in designer or by editing T4 template. When you want to edit T4 template (your model .tt file) try to modify this:
public string NavigationProperty(NavigationProperty navProp)
{
var endType = _typeMapper.GetTypeName(navProp.ToEndMember.GetEntityType());
return string.Format(
CultureInfo.InvariantCulture,
"{0} {1} {2} {{ {3}get; {4}set; }}",
AccessibilityAndVirtual(Accessibility.ForNavigationProperty(navProp)),
navProp.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType,
_code.Escape(navProp),
_code.SpaceAfter(Accessibility.ForGetter(navProp)),
_code.SpaceAfter(Accessibility.ForSetter(navProp)));
}
in this way:
public string NavigationProperty(NavigationProperty navProp)
{
var navigationPropertyName = _code.Escape(navProp);
var match = System.Text.RegularExpressions.Regex.Match(navigationPropertyName, "^(?<a>.+)Id$");
if(match.Success)
navigationPropertyName = match.Groups[1].Value;
var endType = _typeMapper.GetTypeName(navProp.ToEndMember.GetEntityType());
return string.Format(
CultureInfo.InvariantCulture,
"{0} {1} {2} {{ {3}get; {4}set; }}",
AccessibilityAndVirtual(Accessibility.ForNavigationProperty(navProp)),
navProp.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType,
navigationPropertyName,
_code.SpaceAfter(Accessibility.ForGetter(navProp)),
_code.SpaceAfter(Accessibility.ForSetter(navProp)));
}
来源:https://stackoverflow.com/questions/41261167/entity-framework-tt-template-navigation-property-name-based-on-foreign-key-id