安装和更新布尔或INT并不总是工作并不、布尔、工作、INT

2023-09-05 04:22:51 作者:繁华落幕已不再╮

使用实体框架5,给定一个对象使者存在于数据库中,有位属性发表,在EF的previous版本我会更新它是这样的:

Using Entity Framework 5, Given an object messenger that exists in the database, with bit property published, in previous versions of EF I would update it like this:

using (var c = new EFContext())
{
    Data.Messenger cm = new Messenger { MessageId = messageId };
    c.Messengers.Attach(cm);
    cm.Published = newPublishedValue;
    c.SaveChanges();
}

不过,使用EF5,这个工作如果 newPublishedValue ,但如果 newPublishedValue ,不进行任何更改到数据库。同样,这种模式不会将整数值为0。

However, using EF5, this works if newPublishedValue is true, but if newPublishedValue is false, no changes are made to the database. Likewise, this pattern will not set integer values to 0.

这是怎么回事吗?

更换

c.Messengers.Attach(cm);

c.Entry(cm).State = System.Data.EntityState.Modified;

解决了问题,但如果EF5不会更新我的新Data.Messenger 这是一个默认的结构值的属性,不用于呈现的连接方法有点用处?

Fixes the issue, but if EF5 won't update properties of my new Data.Messenger that are of a default struct value, doesn't that render the Attach method a bit useless?

我是什么在这里失踪?

推荐答案

这只是曾在previous版本可能当你使用从 EntityObject 派生实体或波苏斯与动态代理更改跟踪。在这种情况下,属性setter与code,它设置了一个修改标志时,您分配一个值,这个属性(=调用制定者)无论什么旧覆盖值了。

It only worked in previous versions probably when you have used entities derived from EntityObject or POCOs with dynamic proxy change tracking. In that case the property setter is overridden with code that sets a Modified flag for this property when you assign a value (= call the setter) no matter what the old value was.

使用波苏斯没有动态变化的跟踪代理这是行不通的 - 因为没有版本EF - 因为属性setter是一个数据字段的只是在实体类的分配。变化的跟踪情况通过快照更改跟踪这意味着EF比较,当你调用所采取的实体的快照值连接与当你调用实体有值的SaveChanges 。如果值没有改变外汇基金未检测到变化,不会写的属性UPDATE语句。

Using POCOs without dynamic change tracking proxies it doesn't work - for no version of EF - because the property setter is just an assignment of a data field in the entity class. Change tracking happens by snapshot change tracking which means that EF compares the values of a snapshot of the entity taken when you call Attach with the values the entity has when you call SaveChanges. If the values didn't change EF detects no changes and doesn't write an UPDATE statement for the property.

连接仅用于增加一个实体的上下文不变状态。你的情况,你必须标记属性为修改明确,以确保其在数据库中进行更新,无论原值是什么:

Attach is only for adding an entity to the context in Unchanged state. In your case you have to mark the property as Modified explicitly to ensure that it will be updated in the DB, no matter what the old value was:

c.Entry(cm).Property(x => x.Published).IsModified = true;