mvc entity framework 更新字段增加这个值

mvc entity framework update field incrementing this value

我正在用 Entity Framework 应用程序做一个 MVC

我必须更新一个唯一字段,在 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();
        }

其中 Upload 是 Entity,Upload_id 是身份字段,我需要增加 CantVisits 字段,将当前值加 1。

这个例子让我在行中出错

CantVisits = CantVisits

我不知道这个当前值是多少,我想避免做 select 来获得这个值。

有可能吗?

如果该列不是同一列,而您只想向该列添加一个 属性,那么您可以这样做:

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