我觉得自己像个白痴,我全身都用Google搜索,但我找不到答案。 如何为应用用户的ID 创建外键?我有一节课:
public class Enrollment
{
public int Id { get; set; }
[Required]
public Guid UserId { get; set; }
[ForeignKey("ApplicationUserId")]
public ApplicationUser User { get; set; }
[Required]
[ForeignKey("Major")]
public int MajorId { get; set; }
[ForeignKey("MajorId")]
public Major Major { get; set; }
[Required]
[ForeignKey("Term")]
public int TermId { get; set; }
[ForeignKey("TermId")]
public Term Term { get; set; }
}
我的错误是:
Unable to determine the principal end of an association between the types 'Plasty.Models.Enrollment' and 'Plasty.Models.ApplicationUser'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
我在阳光下尝试了一切。起初,我想让ApplicationUser拥有另一个属性,即Enrollment Id的外键,但这不起作用,所以现在我只是将用户的ID放在Enrollment表中。
以下是我添加到应用程序用户的两个属性:
public virtual Enrollment EnrollmentId { get; set; }
public virtual List<CourseTaken> CoursesTaken { get; set; }
答案 0 :(得分:2)
你很亲密。您缺少用户参数的虚拟声明。
public class Enrollment {
//... other get/set methods
public virtual ApplicationUser User {get; set;}
}
仅当您有多个相同类型的用户时才需要指定ForeignKey名称。
答案 1 :(得分:0)
尝试以下操作以查看是否有帮助。原因在于课堂内的评论。根据Pengivan的回应,&#34;虚拟&#34;在需要的地方添加。
public class Enrollment
{
public int Id { get; set; }
[Required]
// The default column is a string, although it stores a Guid
public string UserId { get; set; }
// If specified, should refer to the field name on this side of the relationship
// As Pengivan stated, not needed unless there are multiple references.
[ForeignKey("UserId")]
public virtual ApplicationUser User { get; set; }
[Required]
public int MajorId { get; set; }
public virtual Major Major { get; set; }
[Required]
public int TermId { get; set; }
public virtual Term Term { get; set; }
}
答案 2 :(得分:0)
你有:
public Guid UserId { get; set; }
[ForeignKey("ApplicationUserId")]
public ApplicationUser User { get; set; }
您指定ApplicationUserId
作为外键,但Enrollment
上的外键属性名称为UserId
。确保名称匹配。 : - )