Lets say I query the database and load a list of items. Then I open one of the items in a detail view form, and instead of re-querying the item out of the database, I create an instance of the item from the datasource in the list.
Is there a way I can update the database record without fetching the record of the individual item?
Here is a sample how I am doing it now:
dataItem itemToUpdate = (from t in dataEntity.items
where t.id == id
select t).FirstOrDefault();
Then after pulling the record I update some values in the item and push the record back:
itemToUpdate.itemstatus = newStatus;
dataEntity.SaveChanges();
I would think there would be a better way to do this, any ideas?
You can also use direct SQL against the database using the context of the datastore. Example:
For performance reasons, you may want to pass in variables instead of a single hard coded SQL string. This will allow SQL Server to cache the query and reuse with parameters. Example:
UPDATE - for EF 6.0
This article as part of Microsoft's Getting Started explains entity states and how to do this:
Add/Attach and Entity States
Look at the section 'Attaching an existing but modified entity to the context'
Now I'm off to read the rest of these tutorials.
If the
DataItem
has fields EF will pre-validate (like non-nullable fields), we'll have to disable that validation for this context:Otherwise we can try satisfy the pre-validation and still only update the single column:
Assuming
dataEntity
is aSystem.Data.Entity.DbContext
You can verify the query generated by adding this to the
DbContext
:It works somewhat different in EF Core:
There may be a faster way to do this in EF Core, but the following ensures an UPDATE without having to do a SELECT (tested with EF Core 2 and JET on the .NET Framework 4.6.2):
Ensure your model does not have IsRequired properties
Then use the following template (in VB.NET):
The code:
The result TSQL:
Note:
The "IsModified = true" line, is needed because when you create the new ExampleEntity object (only with the Id property populated) all the other properties has their default values (0, null, etc). If you want to update the DB with a "default value", the change will not be detected by entity framework, and then DB will not be updated.
In example:
will not work without the line "IsModified = true", because the property ExampleProperty, is already null when you created the empty ExampleEntity object, you needs to say to EF that this column must be updated, and this is the purpose of this line.
You should use the Attach() method.
Attaching and Detaching Objects