Lets say there is an entity Person
with a corresponding set Persons
on a DbContext derived class TestDbContext
:
public class Person
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
Then a batch update using EntityFrameworkExtended can be written like this:
[TestMethod]
public void UpdatePersonName()
{
using (var context = new TestDbContext())
{
// insert 'initial' person to be renamed
context.Persons.Add(new Person {Name = "andyp"});
context.SaveChanges();
Assert.AreEqual(1, context.Persons.Count());
Assert.AreEqual("andyp", context.Persons.Select(p => p.Name).Single());
// update the persons name
context.Persons
.Where(p => p.Id == 1)
.Update(p => new Person {Name = "Pascal"});
// assert that the update has been successful
Assert.AreEqual(1, context.Persons.Count());
Assert.AreEqual("Pascal", context.Persons.Select(p => p.Name).Single());
}
}
Notice that I'm updating only one entity (Id == 1
) but a where condition
selecting more than one entity is of course valid as well. The update expression also allows to change more than one property at once.