Can you update a record without querying it first?

c# entity-framework

Question

Let's imagine that I run a database query and load a list of things. Then, when I open one of the items in a detail view form, I build an instance of that item from the datasource in the list rather than re-querying it from the database.

Is there a method to change the database record without retrieving each item's record separately?

Here is an example of how I now do it:

dataItem itemToUpdate = (from t in dataEntity.items
                                 where t.id == id
                                 select t).FirstOrDefault();

Then, after retrieving the record, I push the record back and change a few values in the item:

itemToUpdate.itemstatus = newStatus;
dataEntity.SaveChanges();

Any suggestions for a better method of doing this are welcome.

1
96
6/13/2013 3:00:38 PM

Accepted Answer

Use the Attach() technique, please.

Object Attachment and Detachment

67
11/18/2010 7:15:16 PM

Popular Answer

Using the context of the datastore, you may also utilize straight SQL against the database. Example:

dataEntity.ExecuteStoreCommand
   ("UPDATE items SET itemstatus = 'some status' WHERE id = 123 ");

You may choose to pass in variables rather than a single hard-coded SQL string for speed reasons. As a result, SQL Server will be able to store the query and reuse it with new parameters. Example:

dataEntity.ExecuteStoreCommand
   ("UPDATE items SET itemstatus = 'some status' WHERE id = {0}", new object[] { 123 });

REVISION - for EF 6.0

dataEntity.Database.ExecuteSqlCommand
       ("UPDATE items SET itemstatus = 'some status' WHERE id = {0}", new object[] { 123 });


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow