2012-04-11 40 views
0

我有一個與新的InputOutputMap相關的新ParameterPart實體。 InputOutputMap有幾個我從數據庫中提取的InputState,我需要關聯InputOutputMap。如何使用MVC和WCF數據服務將此鏈保存到數據庫?我使用下面的代碼(通過Ajax調用被調用,上下文僅在構造函數中的第一個電話被設置),但我得到幾個問題:如何使用WCF數據服務將相關實體的集合保存爲一個實體

  • 當我使用AddLink(如下圖所示),我我能夠在第一次嘗試時添加數據(無論我需要關聯多少個輸入狀態)。但是,如果再次調用該方法(通過ajax),則只能在指定一個輸入狀態時添加數據。如果我有多個輸入狀態,我得到的上下文已經在跟蹤關係。請注意,該方法正在使用ajax調用進行調用。
  • 我已經嘗試過使用SetLink,AddRelatedObject並附加,但每次出現上述情況時都會出現錯誤。有時候,錯誤是上下文已經在跟蹤實體或關係。在其他時候,上下文不跟蹤實體。
  • 當我在方法而不是構造函數中設置上下文時,我沒有得到任何好處。

    if (vm != null) 
        { 
         ParameterPart parameterPart = null; 
    
         // Create a new parameter 
         if (vm.PartNumberId == 0) 
         { 
          // Create an instance of ParameterPart 
          parameterPart = new ParameterPart() 
          { 
           Description = vm.ParameterDescription       
          }; 
    
          // Save the ParameterPart into the database 
          try 
          { 
           ctx.AddToParameterParts(parameterPart); 
           ctx.SaveChanges(); 
          } 
          catch (System.Exception ex) 
          { 
           throw; 
          } 
         } 
         else 
         { 
          // Fetch the existing parameter 
          parameterPart = new ParameterPart(); 
          parameterPart = (from pp in ctx.ParameterParts 
              where pp.PartNumberId == vm.PartNumberId 
              select pp).Single(); 
    
          // Update the ParameterPart from the vm 
          parameterPart.Description = vm.ParameterDescription; 
         } 
    
         if (parameterPart != null) 
         { 
          if (vm.StateValues.Count > 0) 
          { 
           InputOutputMap inputOutputMap = new InputOutputMap(); 
           inputOutputMap.PartNumberId = parameterPart.PartNumberId; 
    
           ctx.AddToInputOutputMaps(inputOutputMap); 
    
           // Prepare a new InputOutputMap 
           foreach (var state in vm.StateValues) 
           { 
            if (state.InputStateId != 0) 
            { 
             // Fetch the inputstate 
             var inputState = (from i in ctx.InputStates 
                  where i.InputStateId == state.InputStateId 
                  select i).Single(); 
    
             try 
             { 
              ctx.AddLink(inputOutputMap, "InputStates", inputState); 
              ctx.SaveChanges(); 
             } 
             catch (System.Exception ex) 
             { 
              throw; 
             } 
            }        
           } 
          } 
         } 
        } 
    

回答

0

的AddLink方法工作作爲期望的。由於數據問題,我得到了一個錯誤。

相關問題