2014-03-02 32 views
0

我在查找SQL表中的記錄是否有任何內容時遇到問題,並且我不確定我出錯的位置。這是我多遠我目前:ado.net實體數據模型找到一行?然後調用if語句

using (var context = new SADWorkshopEntities()) 
     { 
      var query = (from p in context.user_profile 
         where p.deviceID == deviceid 
         select p); 
      if (query == null) 
      { 
       context.user_profile.Add(new user_profile() 
       { 
        deviceID = deviceid, 
        uri = subscriberUri 
       }); 
       context.SaveChanges(); 
      } 

添加設備ID和URI的作品,但自從我加入if語句,我把它放在我想說,如果有那不叫的代碼。沒有記錄具有相同的deviceid然後創建一個新的記錄,然後我會嘗試添加更新記錄查詢是否有記錄,但我掙扎。

感謝

+0

有每個設備中的多個用戶? – Derek

+0

最可能的問題是'if(query == null)'永遠不會返回true,因爲'query'的類型是'IQueryable'(參見延遲執行)。解決辦法是強制執行查詢,其中一種方法是使用'FirstOrDefault();'作爲'B-Lat'建議。 – Leron

回答

0

嘗試

using (var context = new SADWorkshopEntities()) 
     { 
      var query = (from p in context.user_profile 
         where p.deviceID == deviceid 
         select p).FirstOrDefault(); 
      if (query == null) 
      { 
       context.user_profile.Add(new user_profile() 
       { 
        deviceID = deviceid, 
        uri = subscriberUri 
       }); 
       context.SaveChanges(); 
      } 
+0

該解決方案適合您嗎? –

+0

對不起,在幾個小時的尋找之後,我在別處恢復了答案。我認爲這可能工作,無論如何,謝謝。我試圖提出評論,但它不會讓我,因爲我沒有足夠的代表 – user3317526

相關問題