简体   繁体   English

具有断开连接的实体的实体框架奇怪的更新行为

[英]Entity Framework with a disconnected entity Strange update behavior

This is a sample to illustrate the problem 这是一个说明问题的样本

A Person must have a PersonType 一个人必须具有一个PersonType

HasRequired(o => o.PersonType).WithMany(o => o.Persons);

Then using a disconnected entity .When I do , 然后使用断开连接的实体。当我这样做时,

   //Person with ID=4 exists in DB
     Person p = new Person() { PersonId = 4, PersonType= null, Address = ... };                

    //PersonType is null here              
    using (var ctxNew = new Context())
    {
       var entry = ctxNew.Entry(p);
       entry.State = System.Data.Entity.EntityState.Modified;
       ctxNew.SaveChanges(); //Ok. But shouldn't be
    }

For some reason SaveChanges() succeeds without an error. 由于某种原因,SaveChanges()成功执行而没有错误。 But as I understand it should fail validation. 但是据我了解,它应该无法通过验证。 This is a problem for me since I'm getting objects like this from my service layer and I don't want them to fail silently .What's the problem here? 这对我来说是个问题,因为我是从服务层获取此类对象的,并且我不希望它们静默失败。这是什么问题?

The problem here is that when you do: 这里的问题是,当您这样做时:

entry.State = System.Data.Entity.EntityState.Modified;

EF marks as Modified only the specified entity. EF仅将指定的实体标记为“已修改”。 If your entity has other related entities (like 'PersonType' navigation property), they will remain in Unchanged state and will not be sent to the database (and not validated) on SaveChanges method call. 如果您的实体具有其他相关实体(例如'PersonType'导航属性),则它们将保持不变状态,并且在SaveChanges方法调用时将不会发送到数据库(并且未经验证)。

For such properties, you can change their state to Modified by calling SetModifiedProperty method: 对于此类属性,可以通过调用SetModifiedProperty方法将其状态更改为Modified:

entry.SetModifiedProperty("PersonType");

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

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