1

我必须在我们的框架中管理并发,但我无法生成 DbUpdateConcurrencyException。我们使用 SQL Server 2008、EF 6 和 AutoMapper 5。

SQL

ALTER TABLE [Keyword].[Keyword] ADD Rowversion [Rowversion] NOT NULL

模型

[Table("Keyword", Schema = "Mailing")]
public class KeywordModel : _Auditable
{
    [Key]
    public int KeywordId { get; set; }

    public string Name { get; set; }
    public string Hashtag { get; set; }
    public string Namespaces { get; set; }
    public string Html { get; set; }

    [Timestamp]
    [ConcurrencyCheck]
    public virtual byte[] RowVersion { get; set; }
}

视图模型

public class KeywordEditViewModel
{
    [HiddenInput(DisplayValue = false)]
    public int KeywordId { get; set; }

    [Display(Name = "Name")]
    public string Name { get; set; }

    [Display(Name = "Hashtag")]
    public string Hashtag { get; set; }

    [Display(Name = "Namespaces")]
    [Description("Separate namespaces by ','")]
    public string Namespaces { get; set; }

    [Required]
    [AllowHtml]
    [UIHint("MultilineText")]
    [Display(Name = "Html")]
    [Description("Prefix or sufix your razor variables with #")]
    public string Html { get; set; }

    [Timestamp]
    [ConcurrencyCheck]
    public byte[] RowVersion { get; set; }
}

控制器

    [HttpPost]
    public virtual ActionResult Edit(KeywordEditViewModel model, string @return)
    {
        var data = new JsonResultData(ModelState);

        if (ModelState.IsValid)
        {
            data.RunWithTry((resultData) =>
            {
                KeywordManager.Update(model.KeywordId, model, CurrentUser.UserId);
                resultData.RedirectUrl = !string.IsNullOrEmpty(@return) ? @return : Url.Action("Index");
            });
        }

        return Json(data);
    }

商业

    public KeywordModel Update(int id, object viewmodel, int userId)
    {
        var model = Get(id);

        Mapper.Map(viewmodel, model);
        SaveChanges("Update mailing keyword", userId);

        return model;
    }

自动映射器

CreateMap<KeywordModel, KeywordEditViewModel>();
CreateMap<KeywordEditViewModel, KeywordModel>();

在我的测试中,RowVersion 字段在数据库中具有不同的值,但 SaveChange 不会生成异常 DbUpdateConcurrencyException。

SQL 跟踪

UPDATE [Mailing].[Keyword]
SET [Namespaces] = @0, [audit_LastUpdate] = @1
WHERE (([KeywordId] = @2) AND ([RowVersion] = @3))
SELECT [RowVersion]
FROM [Mailing].[Keyword]
WHERE @@ROWCOUNT > 0 AND [KeywordId] = @2 
@0: 'titi' (Type = String, Size = -1)
@1: '09/11/2016 13:35:54' (Type = DateTime2)
@2: '1' (Type = Int32)
@3: 'System.Byte[]' (Type = Binary, Size = 8)
4

1 回答 1

1

迟到总比不到好...

在搜索了这个确切的场景几个小时后,我解决了这个问题。EF、automapper、viewmodels,整九个。经过数十篇文章,终于有人说出了一些让我找到了正确方向的东西,它实际上是一个非常简单的解决方法。

当您进行此调用时: var model = Get(id); 要获取您的当前值,然后将更新映射到顶部,请使用它选择新的行版本。

解决方法是在不跟踪的情况下选择“Get(id)”。问题解决了。在我的情况下,我的 repo 有一个“编辑(实体)”方法,该方法将对象标记为已修改,并在它被分离时附加它。你也许可以在这里做同样的事情。

于 2018-02-15T22:14:46.213 回答