2017-10-21 57 views
0

剛剛開始學習實體框架6,並且無法將數據從我的Web應用程序添加到MySQL數據庫。我覺得我做的一切都正確,但是當我嘗試使用Code First方法向數據庫添加某些內容時,我總是得到一個「System.NullReferenceException:Object reference沒有設置爲對象的實例」。代碼如下所示。實體框架:對象引用未設置爲對象的實例

Customer類:

namespace LibraryManager.Models 
{ 
    public class Customer 
    { 
     public int CustomerId { get; set; } 
     public string Username { get; set; } 
     public string Password { get; set; } 
     public virtual ICollection<Book> BooksRead { get; set; } 

     public Customer() 
     { 
      this.BooksRead = new List<Book>(); 
     } 
    } 
} 

圖書類:

namespace LibraryManager.Models 
{ 
    public class Book 
    { 
     public int BookId { get; set; } 
     public string Name { get; set; } 
     public string Genre { get; set; } 
     public double Rating { get; set; } 
     public Boolean Available { get; set; } 
     public string Author { get; set; } 
     public string Desc { get; set; } 
     public virtual Customer Customer { get; set; } 
    } 
} 

的DatabaseManager

public class DatabaseManager 
{ 

    /** 
    * Adds a book into the database 
    */ 
    public void AddBook(Book book) 
    { 
     using (var ctx = new DatabaseContext()) 
     { 
      ctx.Books.Add(book); -->Error Occurs here 
      ctx.SaveChanges(); 
     } 
    } 
} 

上下文類

public class DatabaseContext : DbContext 
{ 
    public DbSet<Book> Books { get; set; } 
    public DbSet<Customer> Customers { get; set; } 

    public DatabaseContext() : base() 
    { 


    } 
} 

在此先感謝

編輯:

代碼調用AddBook

Book HarryPotter = new Book() { Name = "Chamber of Secrets", Genre = "Fantasy", Rating = 8.6, Available = true, Author = "J.K Rowling" }; 
    DatabaseManager manager = new DatabaseManager(); 
    manager.AddBook(HarryPotter); 
+0

我們可以看到調用AddBook()方法的代碼嗎?我敢打賭你的參數被傳入這個方法是null。 – Ratatoskr

+0

嗨,謝謝你的回覆。我剛剛編輯了我的問題 – user7215621

+0

看到如何在添加之前創建書籍對象會更有趣。 –

回答

0

1日。爲您的CustomerId和BookId屬性添加一個關鍵屬性。根據調用方法的代碼,您的Customer屬性爲null,因此它失敗是因爲它無法與空客戶建立外部關係。因此,要麼在構造函數中指定客戶,要麼在AddBook中使用空檢查器來檢查Customer是否爲null,如果是,則創建新客戶。

public void AddBook(Book book) 
{ 
    using (var ctx = new DatabaseContext()) 
    { 
     ctx.Books.Add(book); 

     if (boot.Customer == null) 
      book.Customer = new Customer(); 

     ctx.SaveChanges(); 
    } 
} 

然而,你不希望創建每本書(我假設)的新客戶,所以需要在你的書構造一個客戶,所以可以在數據庫建立的關係。在你的方法中使用try/catch來處理錯誤也是值得的,以幫助你進行調試和跟蹤。

+1

你不需要添加'[Key]'屬性來使其工作。 'BookId'和'CustomerId'遵循約定(TableName + Id),這已經足夠了。同樣在當前的實體類定義中,'Customer_CustomerId'將成爲Book表中的一個nullabe列。所以你仍然可以保存沒有CustomerId的記錄。在SQL服務器和EF 6中驗證它。我假設它在mysql中的工作方式相同 – Shyju

+0

這也是我的理解,但我傾向於添加Key屬性,僅僅是因爲我有時想在主鍵中指定多個列,通常發現它可以幫助我更容易地實現代碼背後的關係模型。 – Ratatoskr

相關問題