我试图在我的win表单应用中使用EF6。在我的代码中,当我在db中添加一个新对象时,我得到了空引用异常。 实际上InitNewProducts方法中的Products属性为null。我做错了什么?
using System.Data.Entity;
namespace DAL
{
public class CartContext: DbContext
{
public CartContext(): base("DbConnection")
{
}
public DbSet<Product> Products;
}
}
using System.Collections.Generic;
namespace DAL
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set;}
}
}
private void InitNewProducts()
{
using (var context = new CartContext())
{
var product1 = new Product {Id = 1, Name = "SomeProduct1", CartItems = new List<CartItem> {new CartItem {Id = 1} } };
context.Products.Add(product1);
context.SaveChanges();
}
}
答案 0 :(得分:1)
向DbSet<Product>
添加访问者:
public virtual DbSet<Product> Products {get; set;}