문제

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:

http://www.symbolsource.org/Public/Metadata/NuGet/Project/EntityFramework.Extended/1.0.0.20/Release/.NETFramework,Version%3Dv4.0/EntityFramework.Extended/EntityFramework.Extended/EntityFramework.Extended/Extensions/BatchExtensions.cs?ImageName=EntityFramework.Extended

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?

도움이 되었습니까?

해결책 2

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.

다른 팁

You are giving Update a MemberExpression instead of a MemberInit expression and this won't tell you anything useful if you haven't dealt with writing and parsing expressions before. However, this exception is telling you that you have to use a code that initializes a new object's properties.

Update(t => step) // member expression because step is a variable
Update(t=> new Something{ Step=step}) // member init expression 

Simply put, you need to always instantiate some object with at least a property in order to work.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top