我正在玩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