简体   繁体   English

为什么我的代码不更新数据库?

[英]Why Doesn't my Code Update The database?

look at these two codes 看看这两个代码

  1. First: 第一:

     Slide _Slide = DataContext.Slides.SingleOrDefault(rec => rec.Id == _SlideObj.Id); _Slide = _SlideObj; DataContext.SaveChanges(); 
  2. Second: 第二:

     Slide _Slide = DataContext.Slides.SingleOrDefault(rec => rec.Id == _SlideObj.Id); _Slide.Title = _SlideObj.Title; _Slide.Description = _SlideObj.Description; DataContext.SaveChanges(); 

The first code does not update the database but the second updates. 第一个代码不会更新数据库,而是第二个更新。 Why? 为什么? How can I change my code to do update operation in first method? 如何更改我的代码以在第一种方法中执行更新操作? (I like to use first method) (我喜欢用第一种方法)

The first only changes the value of a variable to be a different reference. 第一个仅将变量的值更改为不同的引用。 It doesn't actually update the object in any way. 它实际上不会以任何方式更新对象 The data-context is tracking the object . 数据上下文正在跟踪对象

There is no update because you didn't change anything. 没有更新,因为您没有更改任何内容。 In the first case, you just changed _Slide to point to a different Slide. 在第一种情况下,您只需将_Slide更改为指向其他幻灯片。

The problem of the first approach is by design and has nothing to do with the framework you're using. 第一种方法的问题是设计上的,与您正在使用的框架无关。

By calling: _Slide = _SlideObj; 通过调用:_Slide = _SlideObj;
you are telling _Slide to point on _SlideObj instead, but in-memory, the Title and Description properties for the previous pointer to _Slider remain unchanged. 你告诉_Slide指向_SlideObj,但是在内存中,前一个指向_Slider的指针的Title和Description属性保持不变。

Therefore, this is normal behavior. 因此,这是正常行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM