在EF 5中定义Navigation属性,代码优先迁移

本文关键字:代码 迁移 属性 Navigation EF 定义 | 更新日期: 2023-09-27 17:59:13

查看我的型号

    public class UsersContext : DbContext
        {
            public UsersContext()
                : base("DefaultConnection")
            {
            }
            public DbSet<UserProfile> UserProfiles { get; set; }
            public DbSet<Files> Files { get; set; }
        }
        [Table("UserProfile")]
        public class UserProfile
        {
            [Key]
            [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
            public int UserId { get; set; }
            public string UserName { get; set; }
        }
    [Table("Files")]
    public class Files
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        [Display(Name = "FileID")]
        public int FileID { get; set; }
        [Required]
        [ForeignKey("UserId")] // this is what I have tried
        [Display(Name = "For User")]
        public int UserId { get; set; }
        [Display(Name = "Description")]
        public string Desc { get; set; }
        [Required]
        [Display(Name = "Document Upload")]
        public string DocumentPath { get; set; }
    }

我想要的是在files表中为用户id定义一个外键。我该怎么做。我尝试使用[ForeignKey]属性。但它在PCM中执行update-database -verbose时给了我这个错误。

错误-导航属性"UserId"不是上的声明属性键入"文件"。验证它是否未被明确排除在模型,并且它是一个有效的导航属性。

在EF 5中定义Navigation属性,代码优先迁移

[Table("Files")]
public class Files
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    [Display(Name = "FileID")]
    public int FileID { get; set; }
    [Required]
    [Display(Name = "For User")]
    public int UserId { get; set; }

    [Display(Name = "Description")]
    public string Desc { get; set; }
    [Required]
    [Display(Name = "Document Upload")]
    public string DocumentPath { get; set; }
    [ForeignKey("UserId")] // this is what I have tried
    public virtual UserProfile UserProfile { get; set; }
}