简体   繁体   English

更新项目时,实体框架InvalidOperationException

[英]Entity Framework InvalidOperationException when updating an item

I get an System.InvalidOperationException error which states: 我收到一个System.InvalidOperationException错误,指出:

Additional information: Member 'IsModified' cannot be called for property 'state' because the entity of type 'BatteryItem' does not exist in the context. 附加信息:不能为属性“ state”调用成员“ IsModified”,因为上下文中不存在“ BatteryItem”类型的实体。 To add an entity to the context call the Add or Attach method of DbSet. 要将实体添加到上下文,请调用DbSet的Add或Attach方法。

Haven't I done exactly this? 我没有完全做到这一点吗? That is my method below: 那是我下面的方法:

public void UpdateBatteryState(BatteryItem batItem, BatteryState state)
{
    try
    {
        batItem.state = state.ToString();
        context.BatteryItem.Attach(batItem);
        var entry = context.Entry(batItem);
        entry.Property(x => x.state).IsModified = true;

        Save();
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
     }
}

from that info you should do it this way: 从该信息中,您应该这样做:

public void UpdateBatteryState(BatteryItem batItem, BatteryState state)
{
    try
    {

        context.BatteryItem.Add(batItem);
        batItem.state = state.ToString();

        context.SaveChanges()
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
     }
}

I fixed it by calling EntityState.Modified first then disabling modifications for the properties after that, something like this: 我先通过调用EntityState.Modified修复它,然后在此之后禁用对属性的修改,如下所示:

db.Entry(obj).State = EntityState.Modified;
db.Entry(obj).Property(x => x.Password).IsModified = false;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM