刚刚开始学习实体框架6,我无法将数据从我的网络应用程序添加到MySQL数据库。我觉得我做的一切都是正确的,但我总是得到一个" System.NullReferenceException:对象引用未设置为对象的实例"当我尝试使用Code First方法向数据库添加内容时。代码如下所示。
客户类:
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 :(得分:0)
第一。向CustomerId和BookId属性添加键属性。根据调用方法的代码,您的Customer属性为null,因此它失败了,因为它无法与null客户建立外部关系。因此,要么在构造函数中指定客户,要么在AddBook中指定null检查器以检查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进行错误处理也可以帮助您进行调试和跟踪。