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