LINQ to SQL:在多个表上插入表

时间:2011-08-05 18:10:17

标签: sql linq insert

我有两个表,RESTAURANT和HOURS,REST_ID是两个表之间的关键。当我到第一行代码添加HOUR时,我收到一个错误。该错误要求创建对象的实例,但Intellisence允许我调用该表引用。这是一段代码:

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

2 个答案:

答案 0 :(得分:3)

HOURRESTAURANT内的包含对象。您需要在设置属性之前对其进行实例化(如典型的C#对象):

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

答案 1 :(得分:2)

您尚未在RESTAURANT上创建HOUR对象,因此导航属性为null

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