在 MVC 4 ASP.NET 中设置外键

本文关键字:设置 NET MVC ASP | 更新日期: 2023-09-27 18:36:33

我有 2 个模型,想要创建一个外键关系。基本上每个注释都应该分配给用户。

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
}
[Table("UserNotes")]
public class UserNotes
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int NoteId { get; set; }
    [ForeignKey("UserProfile")]
    public virtual int UserId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public string Added { get; set; }
    public DateTime? Edited { get; set; }  
}

当我尝试添加新的用户注释时,我得到:属性"UserId"上的外键属性在类型"注释"上。做。Models.UserNotes'无效。在依赖类型"注释"上找不到导航属性"用户配置文件"。做。模型.用户注释'。Name 值应为有效的导航属性名称。

我尝试了很多组合,包括类似问题中的组合,但没有一个奏效。

在 MVC 4 ASP.NET 中设置外键

试试这个:

public virtual int UserId { get; set; }
[ForeignKey("UserId")]
public virtual UserProfile User { get; set; }

这样,您可以将外键属性与导航属性配对。

编辑:你也可以这样写:

[ForeignKey("UserProfile")]
public virtual int UserId { get; set; }
public virtual UserProfile UserProfile { get; set; }

这两个代码段给出相同的结果。您的错误消息说缺少"用户配置文件"属性,您只需添加它。