使用entityframework在关系表中插入数据时出错

时间:2012-09-04 14:29:40

标签: c# entity-framework

我是entityframework的新手,并试图将数据插入关系表。以下是我的代码的描述以及发生的错误。

我有两张桌子,

  • 产品

  • ProductInformation

我为这两个表设计了实体,如下所示:

产品的实体:

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

EntityContext类:

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)
------------------------------------------------------

运行上面的代码后,我收到以下错误:对象引用未设置为对象的实例。

我哪里错了?

1 个答案:

答案 0 :(得分:2)

这是空的

prod.ProductInformations

当您尝试向其添加项目时。请更正:

prod.Name = "Product-A";
prod.ProductInformations = new Collection<ProductInfomation>();
prod.ProductInformations.Add(pi);