简体   繁体   English

使用数据注释指定外键

[英]Specify Foreign Key with Data Annotations

I am using the newest version of ASP.NET Entity Framework Code First. 我正在使用最新版本的ASP.NET实体框架代码优先。

If I have two classes as follows: 如果我有两个班级,如下所示:

public class Student
{
    public int ID { get; set; }
}

public class Classroom
{
    public int ID { get; set; }
    public Student Student { get; set; }
}

Is there a way for me to use Data Annotations so that when the Classroom table is generated, it knows that I want a ForeignKey to exist in Classroom called StudentID? 有没有一种方法可以使用数据注释,以便在生成Classroom表时知道我希望在Foreignroom中存在一个称为StudentID的ForeignKey? I know how to do it with FluentAPI, but if I could get it done with Data Annotations it would make my application much more simple. 我知道如何用FluentAPI做到这一点,但是如果我能用数据注释完成它,那将使我的应用程序更加简单。 I also would like to avoid having a separate StudentID property in the actual object model because it seems repetitive. 我还想避免在实际的对象模型中使用单独的StudentID属性,因为它似乎是重复的。

public class Student
{
public int ID { get; set; }
}

public class Classroom
{
public int ID { get; set; }
public Student Student { get; set; }

[ForeignKey("Student")]
public int StudentId {get; set;}



}

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

相关问题 如何在EF数据注释中指定外表键? - How to specify foreign table key in EF Data Annotations? 使用数据注释创建外键 - Create Foreign Key using Data Annotations 实体框架 - 代码优先 - 数据注释 - 不必要的外键列 - Entity Framework - Code first - Data annotations - Unnecessary foreign key columns 如何使用数据注释在实体框架中设置外键? - How to set up foreign key in Entity Framework with data annotations? 关键和必需数据注释 - Key and Required data annotations 如何在带有数据注释的实体框架中检索外键关系中的列子集 - How to retrieve a subset of columns in a foreign-key relationship in Entity Framework with Data Annotations 我可以使用Entity Framework Code First数据注释创建双向外键关系吗? - Can I create a bidirectional foreign key relationship using Entity Framework Code First data annotations? 如何使用实体框架在FluentAPI /数据注释中定义外键可选关系? - How do I define Foreign Key Optional Relationships in FluentAPI/Data Annotations with the Entity Framework? FluentNhibernate,指定或自动生成外键字段? - FluentNhibernate, specify or autogenerate Foreign Key field? 实体框架:指定外键约束名称 - Entity Framework: Specify foreign key constraint name
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM