实体框架TT模板

编程入门 行业动态 更新时间:2024-10-26 05:27:05
本文介绍了实体框架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模板

本文发布于:2023-07-27 13:56:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1222731.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实体   框架   模板   TT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!