When I run this code I get an exception at the Update method
public void UpdateTeststep(Teststep step)
{
_context.Teststeps.Where(t => t.TeststepId == step.TeststepId).Update(t => step);
_context.SaveChanges();
}
{"The update expression must be of type MemberInitExpression.\r\nParametername: updateExpression"}
What is wrong with my updateExpression?
Thats the source code of the Update method:
Line 454:
var memberInitExpression = updateExpression.Body as MemberInitExpression;
if (memberInitExpression == null)
throw new ArgumentException("The update expression must be of type MemberInitExpression.", "updateExpression");
Why is the value I pass null? Do I pass my teststep in the wrong way?
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.