如何为应用程序用户(User)创建外键?, AspNetUser?)在Code First MVC应用程序



我觉得自己像个白痴,我到处搜索,但我找不到答案。如何创建应用程序用户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; }

你很接近了。你在user形参上缺少一个虚声明。

public class Enrollment {
    //... other get/set methods
    public virtual ApplicationUser User {get; set;}
}

指定ForeignKey名称只有当您有多个相同类型的用户时才需要。

尝试以下操作,看看是否有帮助。原因在类内的注释中。Per Pengivan的回答是,在需要的地方也添加了"虚拟"。

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; }
}

你有:

public Guid UserId { get; set; }
[ForeignKey("ApplicationUserId")]
public ApplicationUser User { get; set; }

指定ApplicationUserId为外键,但Enrollment上的外键属性名称为UserId。确保名字匹配。: -)

相关内容

  • 没有找到相关文章

最新更新