Entity Framework
EF 3.5 vs EF 4 vs EF 5 vs EF6
EF performance techniques
Errors:
Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist
Add the following errors to avoid JSON exceptions in WebAPI Config
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
Change Tracker
Add vs Attach :
Add
Errors:
Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist
Add the following errors to avoid JSON exceptions in WebAPI Config
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
Change Tracker
Add vs Attach :
Add
- The AddObject method is for adding newly created objects that do not exist in the database. The entity will get an automatically generated temporary EntityKey and its EntityState will be set to Added. When SaveChanges is called, it will be clear to the EF that this entity needs to be inserted into the database.
- On the other hand, Attach is used for entities that already exist in the database. Rather than setting the EntityState to Added, Attach results in an Unchanged EntityState, which means it has not changed since it was attached to the context. Objects that you are attaching are assumed to exist in the database. If you modify the objects after they’ve been attached, when you call SaveChanges the value of the EntityKey is used to update (or delete) the appropriate row by finding its matching ID in the db table.
If you have an entity that you know already exists in the database but which is not currently being tracked by the context-as your case- then you can tell the context to track the entity using the
Attach
method on DbSet
. So in summary what Attach
method do is track the entity in the context and change its state to Unchanged
. When you modify some property after that the tracking changes will change its state to Modified
for you. In the case you expose above you are telling explicitly that state is Modified
but that also attach the entity to your context. You can find a detailed explanation in this post.
No comments:
Post a Comment