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

时间:2012-08-15 10:15:59

标签: c# linq-to-sql

为什么下面的实体不会更新?它们在Get上为null并且在Save(在db中)之后保持为null,即使stocktakeid变量具有值。

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

1 个答案:

答案 0 :(得分:2)

您正在将实体从context本地更改为GetPipelineState(),然后将SubmitChanges()本地context调用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,他们通常会这样做,但如果您手动编写类并忘记实现这些,则不会,或者如果表没有主键(在这种情况下,无论如何都无法对给定行进行更新,因为它无法识别,并且代码生成将这些现在无意义的接口的实现作为优化)