0

我試圖使用代碼首先EF具有這些屬性創建一個表:代碼首先遷移創建另外的屬性

public class HistoryRead 
{ 
    [Key] 
    public int Id { get; set; } 

    [Required] 
    public int Book_Id { get; set; } 

    [Required] 
    [StringLength(128)] 
    public string User_Id { get; set; } 

    public virtual AspNetUser AspNetUser { get; set; } 

    public virtual Book Book { get; set; } 
} 

和我加了關係需要兩個表:

public partial class AspNetUser 
{ 
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] 
    public AspNetUser() 
    { 

     HistoryReads = new HashSet<HistoryRead>(); 

    } 

    public string Id { get; set; } 

    [Display(Name = "Email")] 
    [DataType(DataType.EmailAddress)] 
    [StringLength(256)] 
    public string Email { get; set; } 

    public virtual ICollection<HistoryRead> HistoryReads { get; set; } 

} 

和:

public partial class Book 
{ 
    public Book() 
    { 

     HistoryReads = new HashSet<HistoryRead>(); 
    } 
    [Key] 
    public int Book_id { get; set; } 

    [Required] 
    [Display(Name ="User Name")] 
    [StringLength(128)] 
    public string User_ID { get; set; } 



    public string UrlSlug { get; set; } 



    [Required] 
    [Display(Name = "Title Name")] 
    [StringLength(70,MinimumLength =3)] 
    public string Book_name { get; set; } 


    public virtual ICollection<HistoryRead> HistoryReads { get; set; } 

} 

然後我運行遷移並得到這個結果!

public override void Up() 
    { 
     CreateTable(
      "dbo.HistoryReads", 
      c => new 
       { 
        Id = c.Int(nullable: false, identity: true), 
        Book_Id = c.Int(nullable: false), 
        User_Id = c.String(nullable: false, maxLength: 128), 
        AspNetUser_Id = c.String(maxLength: 128), 
       }) 
      .PrimaryKey(t => t.Id) 
      .ForeignKey("dbo.AspNetUsers", t => t.AspNetUser_Id) 
      .ForeignKey("dbo.Book", t => t.Book_Id, cascadeDelete: true) 
      .Index(t => t.Book_Id) 
      .Index(t => t.AspNetUser_Id); 

    } 

如您在遷移看到生成的代碼我得到了所謂的「AspNetUser_Id」額外的屬性,我不需要,即使當我試圖將其刪除,並繼續我的工作,我從DB側異常。 。所以如何解決這個問題,謝謝...

回答

0

這正是我所期待的遷移。您在HistoryRead內部有一個虛擬的AspNetUser,EF創建一個AspNetUser_Id以將其與您的用戶相匹配。它不知道你想用User_Id作爲鍵。這是拋出異常的原因。

它在書上工作的原因是因爲它使用了_Id的約定,並且它知道它是本書的外鍵。

我建議你從你的模型中刪除User_Id和Book_Id。英孚將負責關係和它需要的外鍵。這樣模型將變得更清潔,並且您可以通過虛擬方式訪問它。

如問,如何將新關係添加到對象的示例。

var historyObject = dbContext.Set<HistoryRead>().GetById(1); 
var bookObject = dbContext.Set<Book>().GetByTitle("Example"); 
historyObject.Book = bookObject; 
dbContext.Set<HistoryRead>().Update(historyObject); 
await dbContext.SaveChangesAsync(); 
+0

我已經有之前創建1個星期前保持相同的屬性和關係的另一個表,但是當我用它的遷移創建它沒有任何額外的屬性! –

+0

嗯,這很奇怪。我會做一些研究並回到它。 –

+0

好的,謝謝你的建議 –