2015-06-24 104 views
1

見我的模型在EF 5定義導航屬性,代碼首先遷移

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

我想是定義在文件表中的用戶ID的外鍵。我該怎麼做。我嘗試使用[ForeignKey]屬性。但它在PCM中執行update-database -verbose時給我這個錯誤。

錯誤 - 導航屬性'UserId'不是 類型'文件'的聲明屬性。驗證它是否未被明確地從 模型中排除,並且它是有效的導航屬性。

+0

1.你能告訴你嘗試過的代碼? 2.你有什麼錯誤? 3.如果你已經有數據並添加一個不可爲空的關係,你當然應該更新你的數據... –

+0

@RaphaëlAlthaus請看我的編輯.. –

回答

2
[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; } 
} 
+0

工作得很好! –