2011-04-11 95 views
1

你能幫忙嗎?我敢打賭,這並不是一件困難的事情。但對於EF來說並不陌生,面臨着週末的最後期限。我想用值更新表格,但主鍵是標識列。所以我的任務是這樣的..如果它存在,更新..如果它不添加到
表..這是我的代碼..並卡在這其他部分..!實體框架更新表4/mvc 3!

表結構是這樣的

主鍵表 - 系統:SYSTEMID,的SystemName

外鍵表 - SystemConfiguration:SystemConfigurationId,SYSTEMID,SystemRAM,SystemHard磁盤

 public void SaveSystemConfigurations(SystemConfiguration systemConfig) 
     { 
       var config = (from s in Context.SystemConfiguration 
         where s.SystemId == systemConfig.SystemId 
          select s).FirstOrDefault(); 

      if (config == null) 
      { 
       Context.SystemConfigurations.AddObject(systemConfig); 
       Context.SaveChanges(); 
      } 
      else 
      { 
       // EntityKey systemConfigKey= new EntityKey("systemConfig", "systemConfigId", config.SystemConfigurationId); 
       Context.SystemConfigurations.Attach(systemConfig); 
       Context.SaveChanges(); 

      } 
     } 

回答

1

試試這個:

 public void SaveSystemConfigurations(SystemConfiguration systemConfig) 
     { 
       var config = (from s in Context.SystemConfiguration 
         where s.SystemId == systemConfig.SystemId 
          select s).FirstOrDefault(); 

      if (config == null) 
      { 
       Context.SystemConfigurations.AddObject(systemConfig); 
      } 
      else 
      { 
       config.Attribute = value; // Do your update here 

      } 
      Context.SaveChanges(); 
     } 

編輯。它應該是配置不是systemConfig。

+0

智能感知不給任何.Attibute? – hillary 2011-04-11 01:23:33

+0

是的。 。屬性只是一個例子。用您想要更新的屬性替換.Attribute。例如。 config.DateModified = DateTime.Now;等等 – ysrb 2011-04-11 01:28:26

+0

謝謝.. ysrb..this作品像一個魅力..!我正在進一步研究,如果theres更好的解決方案..不是手動設置這麼多列.. – hillary 2011-04-11 02:17:21

1

ApplyCurrentValues方法將標量屬性應用於匹配相同鍵的實體。我的假設是你正在修改一個真實的實體(一個具有有效實體鍵的對象)。

這會工作:

var eSet = config.EntityKey.EntitySetName; 
Context.ApplyCurrentValues(eSet, systemConfig); 
Context.SaveChanges(); 
+0

這是你的意思嗎? EntityKey key = new EntityKey(「Context.SystemConfigurations」,「SystemConfigurationId」,config.SystemConfigurationId); var eSet = key.EntitySetName; Context.ApplyCurrentValues(eSet,systemConfig);但沒有,這不是工作.. – hillary 2011-04-11 02:13:52

+0

不會工作,直到我設置systemConfig.SystemConfigurationId = key.value ..但爲什麼我們必須手動做到這一點?!我錯過了一些! – hillary 2011-04-11 02:28:14

+0

如果您再給我一些關於systemConfig來自何處的背景信息,我會更新我的文章併爲您提供更「現代」的解決方案。 – Nix 2011-04-13 00:53:07

1
public void SaveSystemConfigurations(SystemConfiguration systemConfig) 
    {  
    var context = new EntitiesModel(); 
    //here is the name of the partial class created on the Context area of the edmx designer.cs 
    var config = (from s in context.SystemConfiguration 
        where s.SystemId == systemConfig.SystemId 
         select s).FirstOrDefault(); 
    context.ApplyCurrentValues(config.EntityKey.EntitySetName, systemConfig); 
    // systemConfig comes from the view with values set by the user 
    // you dont have to manually need to map one value at the time 
    context.SaveChanges(); 
    }