Bronek
Bronek

Reputation: 11235

LinqToEntity - updating all records

I'm going to modify only one property in all records of a one database table and I don't want to materialize all of the records (as it is done by method ToList() and then iterating through the collection of entities, and then commit). I use EF (5.0, NET 4.0) and linq (thus LinqToEntity).

I mean I want to find the linq counterpart for the following SQL statement:

UPDATE Table
SET Property='NewValue';

Is it possible?

Upvotes: 0

Views: 70

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

You can use ExecuteSqlCommand:

contex.Database.ExecuteSqlCommand("UPATE Table SET Property = @p0", value)

Upvotes: 1

Dismissile
Dismissile

Reputation: 33071

You can run SQL code through the context without using db.SaveChanges:

using(var db = new YourDbContext())
{
    db.Database.ExecuteSqlCommand("UPDATE TABLE SET PROPERTY='NewValue'");
}

If you need to parameterize the value(s) then you can do that as well:

db.Database.ExecuteSqlCommand("UPDATE TABLE SET PROPERTY=@Property",
    new SqlParameter("@Property", someVariable));

Upvotes: 2

Related Questions