我正在MVC
使用Entity Framework
应用
我必须更新一个唯一字段,在1中自动增加此值。
ConnectionEntities _db;
public void AddingVisits(long upload_id)
{
var upload = new Uploads() { Upload_id = upload_id, CantVisits = CantVisits + 1 };
_db.Uploads.Attach(upload);
_db.Entry(upload).Property(x => x.CantVisits).IsModified = true;
_db.Configuration.ValidateOnSaveEnabled = false;
_db.SaveChanges();
}

上传是Entity
,Upload_id是缩进字段,我需要增加CantVisits
字段,将1加到当前值。
这个例子让我在行
中出错CantVisits = CantVisits
我不知道这个当前值是什么,我想避免使用select
来获取此值。
这是可能的吗?
答案 0 :(得分:1)
如果该列不是标识,并且您只想向该属性添加一个,则可以执行此操作:
var upload = new Uploads() { Upload_id = upload_id };
//Attach the existing entity to the context
_db.Uploads.Attach(upload);
// due to you set a property, the EF change tracker will detect your entity was modified, if you haven't disabled it
upload.CantVisits+=1;
_db.SaveChanges();
或将实体状态更改为Modified
:
var upload = new Uploads() { Upload_id = upload_id };
// due to you set a property the entity change tracker will detect your entity was modified, if you haven't disabled it
upload.CantVisits+=1;
context.Entry(upload).State = EntityState.Modified;
_db.SaveChanges();