user841123
user841123

Reputation:

Error while Inserting data in relational table using entityframework

I am new to entityframework, and was trying to insert data into relational tables. Below is the description of my code and what error occured.

I have two tables,

I have designed the entities for both the tables like following:

Product-Entity:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<ProductInfomation> ProductInformations { get; set; }
}

ProductInformation-Entity:

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 Class:

public class EF : DbContext
{
    public DbSet<Product> Products { get; set; }
    public DbSet<ProductInfomation> ProductInformations { get; set; }
}

To insert data into relational table, I`m following below procedure:

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

Database schema:

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

After running above code I get following error: Object reference not set to an instance of an object.

where am I going wrong?

Upvotes: 2

Views: 632

Answers (1)

petro.sidlovskyy
petro.sidlovskyy

Reputation: 5093

This is null

prod.ProductInformations

when you are trying to add item to it. Please correct to:

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

Upvotes: 2

Related Questions