Pierre
Pierre

Reputation: 1667

Adding new entry to DataContext db Cause null reference

I'm a bit new to DataContext but it should still be simple.

I am developing a bidding site where there are many "Products" with each products many "Bids".
I have 2 tables (persisted in .NET to a DataContext Model):
BIDPRODUCT (with auctionID as primary key)
BIDENTRY (with auctionID as foreign key)
RELATIONSHIP: BIDPRODUCT --> BIDENTRY

I am trying to add 1 product with 1 linked bidentry to the db as such: (List<Products> and List<BidEntries> is pre-populated)

        DBDataContext db = new DBDataContext();
        BidProduct p = Products.First();
        BidEntry b = Bids.Where(bi => bi.auctionId == p.auctionId).First();

        p.BidEntries.Add(b);

        db.BidProducts.InsertOnSubmit(p);
        db.SubmitChanges(); 

When p.BidEntries.Add(b) is called I get a null reference on BidEntries!? if I try a = new on BidEntries I still get a null reference.

What is this!?

Upvotes: 1

Views: 575

Answers (1)

Oded
Oded

Reputation: 499352

Have you initialized p.BidEntries to a List<BidEntries>?

The error suggests that it isn't.

You need to ensure that after this point in your code:

 BidProduct p = Products.First();

p.BidEntries is not null - either assign a new List<BidEntry>() to it or ensure that each product has a non null BidEntries property.

Upvotes: 1

Related Questions