Updating & deleting entities

There really isn’t very much for me to say about updating and editing entities. Changing a property is changing a property. As for deleting? Well, you need to call a different method depending on which API you’re using (ObjectContext.DeleteObject() or DbSet<T>.Remove()), and I’ve already told you that the entities aren’t actually deleted until after the database is updated by a call to SaveChanges().

But there is one thig we haven’t discussed: What happens to an entity when an entity it is related to is removed from the database? Let’s look at how that works:

It all depends on the nullability of the foreign key. That determines whether the relationship is optional or required. If the foreign key can be null, the relationship is optional, and the Entity Framework will simply set the appropriate navigation and scalar properties to null.

If, on the other hand, the foreign key is not nullable, then the Entity Framework will mark those entities for deletion as well:

Image

Actually, what I just told you isn’t quite true. That’s the default behavior for one-to-many relationships, and it’s almost always what you want. If you’re working with the Designer, you can check it (and change it, it you need to) by selecting an association and looking at the Properties Window:

Image

If you’re working with Code First, you’ll get cascade behavior by default, but you can turn it off using the WillCascadeOnDelete() Fluent API method:


modelBuilder.WillCascadeOnDelete(false)



Image Take A Break

Well, was I right? Did Entity Framework behave the way you would have expected it to, based on your .NET experience? I hope so.

Why don’t you take a break now, before you complete the Review and we take a closer look at how this whole “change tracking” thing works?


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset