tonyedwardspz
tonyedwardspz

Reputation: 1875

Object returning null after creating object

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

Upvotes: 0

Views: 227

Answers (1)

dotnetom
dotnetom

Reputation: 24901

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; }

Upvotes: 4

Related Questions