简体   繁体   中英

Entity Framework with a disconnected entity Strange update behavior

This is a sample to illustrate the problem

A Person must have a 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. 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. 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.

For such properties, you can change their state to Modified by calling SetModifiedProperty method:

entry.SetModifiedProperty("PersonType");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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