Susan
Susan

Reputation: 1832

LINQ to SQL: table insert on multiple tables

I have two tables, RESTAURANT and HOURS with REST_ID as the key between the two tables. i receive an error when I get to the first line of code to add HOURs. The error asks to create an instance of the object but Intellisence allows me to call that table reference. Here is a snipped of the code:

RESTAURANT addRest = new RESTAURANT();
    addRest.REST_NAME = r_name;
    addRest.REST_STREET1 = r_street;
    addRest.REST_PHONE = r_phone;
    addRest.REST_WEBSITE = r_web;
    addRest.REST_DESC = r_desc;
    addRest.HOUR.HOURS_SUN = h_su;
    addRest.HOUR.HOURS_MON = h_mo;
    addRest.HOUR.HOURS_TUE = h_tu;
    addRest.HOUR.HOURS_WED = h_we;
    addRest.HOUR.HOURS_THU = h_th;
    addRest.HOUR.HOURS_FRI = h_fr;
    addRest.HOUR.HOURS_SAT = h_sa;
    addRest.HOURReference.EntityKey = new EntityKey("FVTCEntities.HOURS", "HOURS", 1);
    db.AddToRESTAURANTs(addRest);
    db.SaveChanges();

Upvotes: 2

Views: 666

Answers (2)

David Hoerster
David Hoerster

Reputation: 28711

HOUR is a contained object inside of RESTAURANT. You need to instantiate it before setting properties on it (like a typical C# object):

addRest.HOUR = new HOUR();
addRest.HOUR.HOURS_SUN = h_su;
...

Upvotes: 3

StriplingWarrior
StriplingWarrior

Reputation: 156748

You haven't created an HOUR object on your RESTAURANT, so that navigation property is null.

...
addRest.REST_DESC = r_desc;
addRest.HOUR = new HOUR();
addRest.HOUR.HOURS_SUN = h_su;
...

Upvotes: 2

Related Questions