我如何传递MemberInitExpression对象

时间:2014-04-24 09:33:37

标签: c# entity-framework func entity-framework-extended

当我运行此代码时,我在Update方法

中得到一个异常
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"}

我的updateExpression有什么问题?

这是Update方法的源代码:

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

第454行:

var memberInitExpression = updateExpression.Body as MemberInitExpression;
                if (memberInitExpression == null)
                    throw new ArgumentException("The update expression must be of type MemberInitExpression.", "updateExpression");

为什么我传递的值为null?我是否以错误的方式通过了测试步骤?

2 个答案:

答案 0 :(得分:3)

您正在使用Update更新MemberExpression而不是MemberInit表达式,如果您之前没有处理过写入和解析表达式,这将不会告诉您任何有用的内容。但是,此异常告诉您必须使用初始化新对象属性的代码。

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

简而言之,您需要始终使用至少一个属性实例化某个对象才能工作。

答案 1 :(得分:0)

假设在DbContext派生类Person上有一个实体Persons和相应的集合TestDbContext

public class Person
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
}

然后使用EntityFrameworkExtended进行批量更新可以这样写:

[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());
    }
}

请注意,我只更新了一个实体(Id == 1),但选择多个实体的where condition当然也是有效的。更新表达式还允许一次更改多个属性。