LINQ to SQL:为什么这些实体不更新?

问题描述:

为什么实体没有返回下面的更新?它们在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

你改变实体从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