我是 entityframework 的新手,并试图将数据插入到关系表中。以下是我的代码的描述以及发生了什么错误。
我有两张桌子,
产品
产品信息
我为这两个表设计了实体,如下所示:
产品实体:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<ProductInfomation> ProductInformations { get; set; }
}
ProductInformation-实体:
public class ProductInfomation
{
public int Id { get; set; }
public string Description { get; set; }
public string BatchNumber { get; set; }
public DateTime ProductedOn { get; set; }
public virtual Product Product { get; set; }
}
实体上下文类:
public class EF : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<ProductInfomation> ProductInformations { get; set; }
}
要将数据插入关系表,我遵循以下过程:
EF objEf = new EF();
ProductInfomation pi = new ProductInfomation();
pi.Description = "Best product in XYZ-Segment";
pi.BatchNumber = "B001";
pi.ProductedOn = DateTime.Now;
Product prod = new Product();
prod.Name = "Product-A";
prod.ProductInformations.Add(pi); // This code throws exception.(Object reference not set to an instance of an object)
objEf.Products.Add(prod);
objEf.SaveChanges();
数据库架构:
Product:
Id INT IDENTITY PRIMARY KEY,
Name VARCHAR(200)
------------------------------------------------------
ProductInformation:
Id INT IDENTITY PRIMARY KEY,
Description VARCHAR(500),
BatchNumber VARCHAR(200),
ProductedOn DATETIME,
Product_Id INT REFERENCES Product(Id)
------------------------------------------------------
运行上述代码后,出现以下错误:对象引用未设置为对象的实例。
我哪里错了?