0

I'm playing around with ASP.net, using a code first approach to create and use a database.

Using the code below I get an exception of type 'System.NullReferenceException' Object reference not set to an instance of an object (see code for specific line).

When I step through the application, the variable in question, 'p' has a value of {Code_first_database.Models.Product}, not null.

I've looked at What is a NullReferenceException and how do I fix it? and What does “Object reference not set to an instance of an object” mean? but I still cant seem to see the problem.

Any help much appreciated.

HomeController.cs

namespace Code_first_database.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            Models.Product p = new Models.Product("Soft331", "Book");
            using (var db = new Models.ProductDB())
            {
                db.products.Add(p); // **EXCEPTION THROWN HERE**
                db.SaveChanges();
                ViewBag.Message = "The number of products so far is " +
                    db.products.Count().ToString();
            }

            return View();
        }
    }
}

Product.cs

namespace Code_first_database.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Product_Code { get; set; }
        public string Product_Name { get; set; }
        public float Price { get; set; }
        public int Stock { get; set; }

        public Product(string p_code, string p_name)
        {
            Product_Code = p_code;
            Product_Name = p_name;
        }
    }
}

ProductDB.cs

namespace Code_first_database.Models
{
    public class ProductDB : DbContext
    {
        public DbSet<Product> products;

        public ProductDB() : base("DefaultConnection")
        {

        }
    }
}

Thanks Tony

2
  • Does your db variable actually have a non-null products property? Commented Oct 18, 2014 at 13:57
  • I dont think so, and I haven't added one. How would I check? Commented Oct 18, 2014 at 14:05

1 Answer 1

4

If I am not mistaken you need to use properties instead of variables in Entity Framework. Change

public DbSet<Product> products;

to

public DbSet<Product> products { get; set; }
Sign up to request clarification or add additional context in comments.

3 Comments

I've added the code for ProductDB.cs to the question. Ive just tried to add 'products = new DbSet<Product>();' into the constructor but it's inaccessible due to it's protection level.
@tonyedwardspz I don't think you need to initialize it, try changing variable to property first
Fantastic. The getter and setter sorted it. Thanks for the help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.