刚刚开始学习实体框架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);
我们可以看到调用AddBook()方法的代码吗?我敢打赌你的参数被传入这个方法是null。 – Ratatoskr
嗨,谢谢你的回复。我刚刚编辑了我的问题 – user7215621
看到如何在添加之前创建书籍对象会更有趣。 –