Update a record without first querying?

2020-01-26 03:51发布

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?

7条回答
不美不萌又怎样
2楼-- · 2020-01-26 04:53

Generally speaking, if you used Entity Framework to query all the items, and you saved the entity object, you can update the individual items in the entity object and call SaveChanges() when you are finished. For example:

var items = dataEntity.Include("items").items;
// For each one you want to change:
items.First(item => item.id == theIdYouWant).itemstatus = newStatus;
// After all changes:
dataEntity.SaveChanges();

The retrieval of the one item you want should not generate a new query.

查看更多
登录 后发表回答