just started learning Entity Framework 6 and am having trouble adding data from my web app to a MySQL database. I feel I'm doing everything right but I always get an "System.NullReferenceException: Object reference not set to an instance of an object" when I try to add something to the database using a Code First approach. The code is shown below.
Customer Class:
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>();
}
}
}
Book Class:
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();
}
}
}
Context Class
public class DatabaseContext : DbContext
{
public DbSet<Book> Books { get; set; }
public DbSet<Customer> Customers { get; set; }
public DatabaseContext() : base()
{
}
}
Thanks in advance
EDIT:
Code calling 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);