简体   繁体   English

在Asp.Net Web Api中的EntityFramework中查找表对象实体以获得更新前的列的当前值

[英]Find Table Object Entity to get Current value of a Column before Updation in EntityFramework in Asp.Net Web Api

I`m new in MVC and want to know how to find a Table object entity using where just before updation. 我是MVC的新成员,想知道如何使用更新之前的位置查找Table对象实体。 My code is as follows:- 我的代码如下:

    public async Task<IHttpActionResult> PutEmployee(int id, Employee model)
{
    Employee emp = db.Employee.Where(x => x.Id == id).FirstOrDefault();
    if(emp!=null)
    {
        if(emp.ImagePath!=model.ImagePath)
        {
            //Code to move image
        }
        db.Entry(model).State = EntityState.Modified; //THIS IS WHERE IT THROWS ERROR
        model.ImagePath = model.ImagePath.Replace("Temp/", "");
        db.Entry(model).Property(x => x.IsDeleted).IsModified = false;
        //Update changes using db.SaveChanges();
    }
}

Code throws error on db.Entry(model).State = EntityState.Modified; 代码在db.Entry(model).State = EntityState.Modified;上引发错误

Attaching an entity of type 'MyProject.Models.Employee' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate

The purpose here is to check if Employee with Id exists and if it exists then check whether the current value of Employee.ImagePath is different from the model passed by the User. 此处的目的是检查具有ID的Employee是否存在,以及是否存在,然后检查Employee.ImagePath的当前值是否与User传递的模型不同。

Any help will be appreciated... 任何帮助将不胜感激...

You don't need to tell the DbContext that the state has changed, it will do that by itself if you change any property. 您无需告诉DbContext状态已更改,如果您更改任何属性,它将自行完成。 So drop (both) lines where you are doing so. 因此,将行都放在这两个行中。

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

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