2012-08-15 31 views
1

爲什麼實體沒有返回下面的更新?它們在Get上爲null,在Save(在db中)之後保持爲null,即使stocktakeid變量具有值。LINQ to SQL:爲什麼這些實體不更新?

protected void GetPipelineState() 
     { 
      InventoryModelDataContext context = new InventoryModelDataContext(this.ConnectionString); 
      var f = from pe in context.StockTakePipelines 
        where pe.StockTakeId == null 
        select pe; 
      this.PipeLine = f; 
     } 

     protected void SavePipelineState() 
     { 
      InventoryModelDataContext context = new InventoryModelDataContext(this.ConnectionString); 
      foreach (StockTakePipeline p in this.PipeLine) 
      { 
       p.StockTakeId = this.StockTakeId; 
      } 
      context.SubmitChanges(); 
     } 

編輯:重新PK

enter image description here

回答

2

你改變實體從context本地GetPipelineState(),然後呼籲context當地SubmitChanges()SavePipelineState()

嘗試更多的東西一樣:

protected IQueryable<StockTakePipeline> GetPipelineState(InventoryModelDataContext context) 
    { 
     return from pe in context.StockTakePipelines 
       where pe.StockTakeId == null 
       select pe; 
    } 

    protected void SavePipelineState() 
    { 
     using(InventoryModelDataContext context = new InventoryModelDataContext(this.ConnectionString)); 
     { 
      foreach (StockTakePipeline p in GetPipelineState(context)) 
      { 
       p.StockTakeId = this.StockTakeId; 
      } 
      context.SubmitChanges(); 
     } 
    } 

編輯:

只是爲別人找到這個問題的註釋。導致實體不更新的另一件事是,如果他們不實現INotifyPropertyChangingINotifyPropertyChanged,他們通常會這樣做,但如果您手動編碼類並忘記實現這些類,或者如果表沒有主類鍵(在這種情況下,無論如何都無法對給定行進行更新,因爲無法識別,代碼gen會將這些現在毫無意義的接口的實現視爲優化)。

+0

是不是每個記錄查詢所有合格記錄的數據庫? – rism 2012-08-15 10:27:22

+0

@rism不,它與你的代碼完全一樣,除了它使用傳入的上下文來生成'IQueryable '。 'foreach'表示查詢執行一次,並且結果通過(對GetPipelineState()的單個調用,對GetEnumerator())的單個隱藏調用,以及MoveNext()中的多個隱藏調用進行迭代,直到它返回false,在'Current'上匹配隱藏的調用以獲得'p'的當前值)。 – 2012-08-15 10:31:31

+0

您對「PipeLine」字段或屬性有何種類型?如果它是'IEnumerable '或'IQueryable ',那麼上面的表現會有相同的表現。如果它是其他東西,那麼上面的內容可能會更快一些(除了「SubmitChanges」有事可做的事情顯然會讓它整體變慢!)。 – 2012-08-15 10:34:13