2011-08-05 54 views
2

我有兩個表,RESTAURANT和HOURS,REST_ID作爲兩個表之間的鍵。當我到達第一行添加HOUR的代碼時,我收到一個錯誤。該錯誤要求創建對象的實例,但Intellisence允許我調用該表引用。下面是代碼的文檔片斷:LINQ to SQL:在多個表上插入表格

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

回答

3

HOURRESTAURANT內部包含的對象。您需要在設置屬性之前將其實例化(如典型的C#對象):

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

您尚未創建在你的餐廳一小時的對象,從而使導航屬性是null

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