实体框架TT模板->基于外键ID的导航属性名称 [英] Entity Framework TT template -> Navigation Property name based on foreign key ID

查看:99
本文介绍了实体框架TT模板->基于外键ID的导航属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下表:

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

我正在使用EF,我想基于外键生成导航属性,除去ID部分,因此我希望拥有导航属性Phone和MobilePhone。尝试调试,但未找到外键存储在哪里。请使用TT模板提供帮助:我应该在哪里修改什么。

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.

推荐答案

您可以通过在设计器中编辑edmx或编辑T4模板来完成。当您想要编辑T4模板(您的模型.tt文件)时,请尝试修改以下内容:

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)));
}

以这种方式:

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)));
}

这篇关于实体框架TT模板->基于外键ID的导航属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆