Reputation: 9856
Recently I've talked to a Java
programmer who told me that Hibernate
is smart enough to detect if an entity has any changes made to it and even if you call an UPDATE
for entity if it has not been modified then no SQL UPDATE
command will be executed.
I am not working with large volumes of data but still I'm curious if the same applies for Entity Framework 5
. In my current project I use Repositories
so the Update
method looks like this:
public virtual void Update(TEntity entity)
{
dbSet.Attach(entity);
context.Entry(entity).State = EntityState.Modified;
context.SaveChanges();
}
this combined with UnitOfWork
let's say I've just submitted to the controller a List
of type News
where News
is an entity. So if in my Action I do something like this :
public ActionResult Edit(List<News> model)
{
foreach (News item in model)
{
unitOfWork.NewsRepository.Update(item);
}
}
what will actually happen if I have items that have not been modified? Do I still make a database query to update the record with the same data or the entity framework is smart enough to just skip it and proceed with the next item?
Upvotes: 1
Views: 439
Reputation: 17579
In order to get the change set which will project to actual queries to database you can either query underlying context or the entity itself ( if it is self tracking entity). (See my answer to this question).
From your example it is not clear if you are using POCO or self-tracking entities, but in both those cases you are missing step of figuring out what was changed in the object when you attach it.
In order to do this, EF should either query db for original object and compare with the one attached, or if it is self-tracking entity, EF will query inner entity changeset to do the update.
UPDATE: In order to sum up what @hvd and I said:
Since we are talking about POCO entities here is what happens:
There are several things you can do
There is this course on Pluralsight ( and there are two newer versions of it with different client side technology stack) which covers this topics and shows how to do change tracking in case you have to change entities out of context.
Upvotes: 1
Reputation:
Entity Framework tracks changes made to objects while they are attached to a context, and will issue UPDATE
statements if you've made changes to the properties, and call SaveChanges
, without needing to set State
to EntityState.Modified
manually.
In your code, you're making the changes when the objects aren't attached to a context. The only way Entity Framework can let this work is by forcing an UPDATE
statement that (re-)sets all fields in the database, even those that remain unchanged.
So, yes, in general, the same does apply to Entity Framework, just not how you're using it.
Upvotes: 1