首页 > 解决方案 > Declare foreign keys using Data Annotation to use ReferentialConstraints collection?

问题描述

Referencing from this old post, I have tried out the voted answer using the sample code below. But it does not returns what the answerer have said it would. The ReferentialConstraints collection for the relationship between Student and Grade turns out to be null. Does anyone knows what I have done incorrectly?

Do I have to declare foreign keys using Data Annotation in order to have values in the ReferentialConstraints collection?

Code Sample for convention #1:

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Grade Grade { get; set; }
}

public class Grade
{
    public int GradeId { get; set; }
    public string GradeName { get; set; }
    public string Section { get; set; }
}

标签: c#sql-serverentity-frameworkentity-framework-6

解决方案


你可以使用这种类型

public int GradeId { get; set; }
[ForeignKey("GradeId")]
public Grade grade { get; set; }

推荐阅读