为什么我在 .NET Core 中应用了工作单元模式,但仍然发生并发冲突?

问题描述

我是新手。我想更新用户的个人资料,但错误。这是我的功能更新/插入的逻辑代码,就我而言,我设置的是 UPDATE

Project -> Options -> Forms

处理请求时发生未处理的异常。 dbupdateConcurrencyException:数据库操作预期影响 1 行,但实际影响 0 行。自加载实体以来,数据可能已被修改删除。有关理解和处理乐观并发异常的信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=527962

这是我的个人资料模型

procedure TForm1.Button1Click(Sender: TObject);
var
  I: Integer;
begin
 for I := 0 to Self.ComponentCount - 1 do
 begin
   if Self.Components[I] is TCustomEdit then
   begin
     (Self.Components[I] as TCustomEdit).Text := '';
   end;
 end;
end;

这是 Update() 和 Save() 的响应式通用

[HttpPost]
public ActionResult UpdateProfile(Profileviewmodel profile,IFormFile? formFile)
{
    if(ModelState.IsValid)
    {
        if(formFile != null)
        {
            string uploadFolder = Path.Combine(_hostingEnvironment.WebrootPath,"Images\\UserImages");
            string uniqueFilename = Guid.NewGuid().ToString() + "_" + formFile.FileName;
            string filePath = Path.Combine(uploadFolder,uniqueFilename);
            formFile.copyTo(new FileStream(filePath,FileMode.Create));
            profile.Avatar = uniqueFilename;
        }

        EcommerceAPI.DataAccess.EFModel.Profile profiletoupdate = new EcommerceAPI.DataAccess.EFModel.Profile()
        {
            FirstName = profile.FirstName,LastName = profile.LastName,Address = profile.Address,};

        if (profile.Avatar != null) profiletoupdate.Avatar = profile.Avatar;
        // I check user in Database. Has user existed before?
        bool IsExisted =  _unitOfwork.ProfileResponsitory.Find(p => p.UserID == profile.UserID) != null; 

        if (IsExisted)
        {
            //Update profile
            _unitOfwork.ProfileResponsitory.Update(profiletoupdate);
        }
        else
        {
            //Insert Profile
            _unitOfwork.ProfileResponsitory.Insert(profiletoupdate);
        }

        try
        {
            _unitOfwork.ProfileResponsitory.Save();
            return View("ViewProfile");
        }
        catch(Exception ex)
        {
            // ==> I gave dbupdateConcurrencyException ef core exception :<
            throw ex; 
        }
    }
    else
    {
        ModelState.AddModelError("","Parrams is invalid");
        return View("ViewProfile");
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)