无法在一列上设置主键和外键

时间:2018-02-01 17:11:23

标签: c# entity-framework-core data-annotations

所以我尝试用EF Core创建一些ASP.NET项目。

我想将一个实体的属性设置为主键,将外键设置为另一个实体的外键。关系是0..1 - 1。我使用DataAnnotations

public class OfficeAssignment
{
    [Key, ForeignKey("InstructorID")]
    public int InstructorID { get; set; }
    public Instructor Instructor { get; set; }
    public string Location { get; set; }
}

但我一直将列InstructorID称为PK,将InstructorID1作为FK ...任何想法,为什么EF表现得像那样,我怎样才能达到目标?

2 个答案:

答案 0 :(得分:1)

您应该尽可能多地遵循惯例而不是配置。 OfficeAssignment实体应该有OfficeAssignmentId PK,如下所示:

public class OfficeAssignment
{
    public int OfficeAssignmentId { get; set; }

    //Notice that Id does not have an uppercase D
    public int InstructorId { get; set; }
    public string Location { get; set; }

    public Instructor Instructor { get; set; }
}

但是,如果您不想遵循常规约定,则ForeignKey属性中的属性名称与声明的位置相反:

public class OfficeAssignment
{
    [Key, ForeignKey("Instructor")]
    public int InstructorId { get; set; }
    public string Location { get; set; }

    public Instructor Instructor { get; set; }
}

而且,如果你想保持编译时安全:

public class OfficeAssignment
{
    [Key, ForeignKey(nameof(Instructor))]
    public int InstructorId { get; set; }
    public string Location { get; set; }

    public Instructor Instructor { get; set; }
}

答案 1 :(得分:0)

[Key]类和OfficeAssignment类中设置主键属性(Instructor)就足够了,我们需要设置这样的属性:

[InverseProperty("Instructor")]

收集CourseAssignments。这将按预期工作。