Entity Framework TT template -> Navigation Property name based on foreign key ID

故事扮演 提交于 2019-12-24 11:13:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!