简体   繁体   English

代码生成:向实体框架添加主键/外键

[英]Code Generation : Add primary key / foreign key to Entity Framework

I'm using EF with database first approach. 我将EF与数据库优先方法结合使用。

I would like to add attribute to the generated code to mark property as primary key / foreign key when it's the case. 我想在生成的代码中添加属性,以将属性标记为主键/外键。

For example, if I have a table User in my database 例如,如果我的数据库中有一个表User

CREATE TABLE User
(
   Id int PRIMARY KEY
);

I would like my generated code to include an attribute that indicate that Id is the primary key. 我希望生成的代码包含一个指示Id是主键的属性。

public partial class User
{
    [PrimaryKey]
    public int Id { get; set; }
}

How could I do that? 我该怎么办?

EDIT : I know about T4 template, I just don't know where to start to modify that file. 编辑:我知道有关T4模板,我只是不知道从哪里开始修改该文件。

I ran into the same problem. 我遇到了同样的问题。 The template file you are looking for appears in the Solution Explorer (in VS2013) as: 您要查找的模板文件在解决方案资源管理器(VS2013)中显示为:

YourDataModelName.tt YourDataModelName.tt

You can modify it to add the [Key] attributes to the generated code by following: 您可以通过以下操作对其进行修改,以将[Key]属性添加到生成的代码中:

Finding a property is Primary Key in POCO Template t4 generator 查找属性是POCO Template t4生成器中的主键

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架代码优先 - 非主键字段的外键 - Entity Framework Code First - Foreign Key to non primary key field 实体框架外键作为主键代码优先 - Entity Framework Foreign Key as Primary Key Code First 如何防止实体框架外键生成? - How to prevent Entity Framework foreign key generation? 实体框架代码优先-通过主键将子实体添加到父实体 - Entity Framework Code First - Add Child Entity to Parent by Primary Key 实体框架两个外键作为主键 - Entity Framework Two foreign keys as primary key 实体框架将主键定义为另一个实体的外键 - Entity Framework define primary key as foreign key to another entity 实体框架代码优先设置的外键和同一表中的主键 - Entity Framework code-first set foreign key with primary key in same table 在Code-First Entity Framework中包含复合主键中的外键 - Include foreign key in composite primary key in Code-First Entity Framework 实体框架代码优先使用具有另一个表的非主键的外键 - Entity Framework Code First approach foreign key with non primary key of another table Entity Framework 5.0非主键的复合外键-可能吗? - Entity Framework 5.0 composite foreign key to non primary key - is it possible?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM