Dabiel Kabuto
Dabiel Kabuto

Reputation: 2862

Efficient way to update a column from a table using LinqSql?

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?

UPDATE:

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

Answers (2)

mohsen
mohsen

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

ilans
ilans

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

Related Questions