Reputation: 2862
In Sql, for example I would do:
UPDATE MyTable SET MyColum='value' WHERE Id=132
How would be the equivalent in a EF Code First database?
Seeing the responses, I need to clarify my question. I am looking for an efficient way to update one column. If I use Single() or any similar function, the performance is very poor for two reasons: 1) There are 2 SQL statements, one for SELECT, and one for UPDATE, 2) The Single function retrieves all columns.
UPDATE MyTable SET MyColum='value' WHERE Id=132
The above sentence is efficient because it is only one transaction and no values are sent to the client from the server. I would like which would be the equivalent sentence in Linq Sql.
Upvotes: 0
Views: 454
Reputation: 1806
I think it is not possible with one transaction.you need first to check that row you want to update is in your table or not
using (MyEntities me=new MyEntities())
{
if( (from t in me.MyTables where mt.Id == 132 select t).Any())
{
MyTable mt= (from t in me.MyTables where mt.Id == 132 select t).Single();
mt.MyColumn= "Value";
me.SaveChanges();
}
}
Upvotes: 0
Reputation: 2727
SingleOrDefault would return the object if exists in the db, or null otherwise:
var row = context.MyTable.SingleOrDefault(x => x.id == 132);
if(row != null) {
row.MyColumn = "Value";
context.SaveChanges();
}
Upvotes: 1