我正在玩ASP.net,使用代碼優先的方法來創建和使用數據庫。創建對象後返回null的對象
使用下面的代碼我得到一個'System.NullReferenceException'類型的異常未設置爲對象實例的對象引用(請參閱特定行的代碼)。
當我遍歷應用程序時,問題變量'p'的值爲{Code_first_database.Models.Product},而不是null。
我已經看過What is a NullReferenceException and how do I fix it?和What does 「Object reference not set to an instance of an object」 mean?但我似乎仍然不能看到問題。
任何幫助非常感謝。
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")
{
}
}
}
感謝 Tony
貴'db'變量實際上有一個非空'products'財產? – 2014-10-18 13:57:02
我不這麼認爲,我還沒有添加。我將如何檢查? – tonyedwardspz 2014-10-18 14:05:59