Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c# - Entity Framework InvalidOperationException when updating an item

I get an System.InvalidOperationException error which states:

Additional information: Member 'IsModified' cannot be called for property 'state' because the entity of type 'BatteryItem' does not exist in the context. To add an entity to the context call the Add or Attach method of DbSet.

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);
     }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...