1.21 jigowatts

Great Scott!

ASP.NET MVCはじめました~MongoDBのデータを更新する

概要

一覧登録とやってきて、今回はMongoDBのデータ更新です。

編集画面はこんな感じになります(デフォルト)。
f:id:sh_yoshida:20160915134020p:plain

環境

更新データの取得

/Users/Edit/57da234368ff011234b23756
一覧画面からの遷移で編集画面を開くときはパラメータにObjectIdを指定してますが、URLがキタナイのでもっと別のわかりやすい一意の値のほうがいいかもしれない。
■UsersController.cs

[HttpGet]
public async Task<ActionResult> Edit(string id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    var model = await _repository.GetByIdAsync(id);
    if (model == null)
    {
        return HttpNotFound();
    }

    return View(model);
}

■UserRepository.cs

public async Task<User> GetByIdAsync(string id)
{
    var collection = GetCollection<User>(Collection);
    return await collection.Find(d => d.Id == id).FirstOrDefaultAsync();
}

あと、型はstringです。最初モデルをObjectId型にしてたんですが、モデルバインディングのときにObjectId型に変換出来なくてエラーになりました。

[BsonId]
public ObjectId Id { get; set; }

BsonRepresentationっていう属性をつけてあげて、string型で定義しておくとうまいことやってくれるようです。

[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }

データの更新

データの更新は条件と値をUpdateメソッドに渡してあげます。
■UserRepository.cs

public async Task UpdateAsync(User document)
{
    var collection = GetCollection<User>(Collection);
    var objId = ObjectId.Parse(document.Id);
    var filter = Builders<User>.Filter.Eq("_id", objId);
    var update = Builders<User>.Update
        .Set("name", document.Name)
        .Set("age", document.Age)
        .Set("email", document.Email)
        .Set("address", document.Address);

    await collection.UpdateOneAsync(filter, update);
}

項目名が文字列なのでちょっと気になりますね。ラムダ式が用意されているのでこっちのほうがいいかも。
■UserRepository.cs

public async Task UpdateAsync(User document)
{
    var collection = GetCollection<User>(Collection);
    var update = Builders<User>.Update
        .Set(d => d.Name, document.Name)
        .Set(d => d.Age, document.Age)
        .Set(d => d.Email, document.Email)
        .Set(d => d.Address, document.Address);

    await collection.UpdateOneAsync(d => d.Id == document.Id, update);
}

単純に更新するだけであればこれでOKですが、複数のユーザが同時に更新した場合、先に更新したユーザのデータが後に更新したユーザに上書きされてしまいます。

楽観的ロック

MongoDBにはトランザクションがありません。トランザクションが必要な要件であればトランザクション機能を持つRDBMSなどを使うほうがいいのでしょう。ただ、そこまで厳密ではないシンプルな要件であれば楽観的ロックで対処できるかもしれません。

モデルにRevisionフィールドを追加します。
■User.cs

[BsonElement("revision")]
public int Revision { get; set; }

更新条件にRivisionフィールドを参照し、更新時にIncメソッドでインクリメントしてあげます。UpdateOneAsyncメソッドは変更した件数を返してくれるので、こいつが1件の場合は成功、それ以外は失敗扱いにしています。
■UserRepository.cs

public async Task<bool> UpdateAsync(User document)
{
    var collection = GetCollection<User>(Collection);
    var builder = Builders<User>.Filter;
    var filter = builder.Eq(d => d.Id, document.Id)
        & builder.Eq(d => d.Revision, document.Revision);

    var update = Builders<User>.Update
        .Set(d => d.Name, document.Name)
        .Set(d => d.Age, document.Age)
        .Set(d => d.Email, document.Email)
        .Set(d => d.Address, document.Address)
        .CurrentDate(d => d.LastModified)
        .Inc(d => d.Revision, 1);

    var result = await collection.UpdateOneAsync(filter, update);
    if (result.IsModifiedCountAvailable && result.ModifiedCount == 1)
    {
        return true;
    }
    return false;
}

最初はDateTime型のLastModifiedフィールドで対応しようと思ったのですが、UTCだし、手間だったのでやめました。

二つブラウザを立ち上げ、同時に編集画面を開きます。この段階ではどちらもRevisionフィールドは同じ値(初期値:1)です。
f:id:sh_yoshida:20160915134139p:plain

まず左側のブラウザで住所をフィラデルフィアへ編集しデータベースを更新します。
f:id:sh_yoshida:20160915134218p:plain

更新が確定するとRevisionが一つ上がっているので、左側のブラウザで更新しようとしても更新対象が見つからずエラーメッセージが表示されるって感じです。
f:id:sh_yoshida:20160915134228p:plain

MongoDBのrevisionフィールドがインクリメントされていることが確認できます(mLabより)。
f:id:sh_yoshida:20160915140014p:plain

MVC

コードを一式載せておきます。

Model

Revisionと、ついでにLastModifiedフィールドを追加しました。
■User.cs

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.ComponentModel.DataAnnotations;

namespace aspnet_mvc5_mongodb.Models
{
    public class User
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }

        [BsonElement("name")]
        [Required]
        public string Name { get; set; }

        [BsonElement("age")]
        public int Age { get; set; }

        [BsonElement("email")]
        [Required]
        public string Email { get; set; }

        [BsonElement("address")]
        public string Address { get; set; }

        [BsonElement("revision")]
        public int Revision { get; set; }

        [BsonElement("last_modified")]
        public DateTime LastModified { get; set; }

    }
}

View

■Edit.cshtml

@model aspnet_mvc5_mongodb.Models.User

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>
@{
    if (ViewBag.ErrorMsg != null)
    {
        <span class="errorMsg">@ViewBag.ErrorMsg</span>
    }
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>User</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Id)
        @Html.HiddenFor(model => model.Revision)
        @Html.HiddenFor(model => model.LastModified)

        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Controller

■UsersController.cs

using aspnet_mvc5_mongodb.Models;
using aspnet_mvc5_mongodb.Repositories;
using aspnet_mvc5_mongodb.Repositories.Abstractions;
using System;
using System.Net;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace aspnet_mvc5_mongodb.Controllers
{
    public class UsersController : Controller
    {
        private readonly IUserRepository _repository;
        public UsersController()
            : this(new UserRepository())
        {

        }
        public UsersController(IUserRepository repository)
        {
            this._repository = repository;
        }

        [HttpGet]
        public async Task<ActionResult> Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var model = await _repository.GetByIdAsync(id);
            if (model == null)
            {
                return HttpNotFound();
            }

            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit(User document)
        {
            if (document == null)
            {
                return HttpNotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    if (await _repository.UpdateAsync(document))
                    {
                        return RedirectToAction("Index");
                    }
                    ViewBag.ErrorMsg = "他のユーザにより更新されています。";
                    return View(document);
                }
                catch (Exception)
                {
                    ViewBag.ErrorMsg = "データ更新に失敗しました。";
                    return View(document);
                }
            }

            return View(document);
        }

        ...
    }
}

リポジトリ

■MongoDB.cs

using MongoDB.Driver;
using System.Configuration;

namespace aspnet_mvc5_mongodb.Repositories
{
    public class MongoDB
    {
        protected static IMongoClient _client;
        protected static IMongoDatabase _database;

        public MongoDB()
        {
            var connectionString = ConfigurationManager.AppSettings["MongoDBConnection"];
            var database = ConfigurationManager.AppSettings["Database"];
            _client = new MongoClient(connectionString);
            _database = _client.GetDatabase(database);
        }

        public static IMongoCollection<T> GetCollection<T>(string collection)
        {
            return _database.GetCollection<T>(collection);
        }

    }
}

■IUserRepository.cs

using aspnet_mvc5_mongodb.Models;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace aspnet_mvc5_mongodb.Repositories.Abstractions
{
    public interface IUserRepository
    {
        Task<User> GetByIdAsync(string id);
        Task InsertAsync(User document);
        Task<bool> UpdateAsync(User document);
        ...
    }
}

新規登録時にRevisionとLastModifiedフィールドの初期値を設定するコードも追加。
■UserRepository.cs

using aspnet_mvc5_mongodb.Models;
using aspnet_mvc5_mongodb.Repositories.Abstractions;
using MongoDB.Driver;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace aspnet_mvc5_mongodb.Repositories
{
    public class UserRepository : MongoDB, IUserRepository
    {
        private static readonly string Collection = "users";

        public async Task<User> GetByIdAsync(string id)
        {
            var collection = GetCollection<User>(Collection);
            return await collection.Find(d => d.Id == id).FirstOrDefaultAsync();
        }

        public async Task InsertAsync(User document)
        {
            document.Revision = 1;
            document.LastModified = DateTime.Now;
            var collection = GetCollection<User>(Collection);
            await collection.InsertOneAsync(document);
        }

        public async Task<bool> UpdateAsync(User document)
        {
            var collection = GetCollection<User>(Collection);

            var builder = Builders<User>.Filter;
            var filter = builder.Eq(d => d.Id, document.Id)
                & builder.Eq(d => d.Revision, document.Revision);

            var update = Builders<User>.Update
                .Set(d => d.Name, document.Name)
                .Set(d => d.Age, document.Age)
                .Set(d => d.Email, document.Email)
                .Set(d => d.Address, document.Address)
                .CurrentDate(d => d.LastModified)
                .Inc(d => d.Revision, 1);

            var result = await collection.UpdateOneAsync(filter, update);
            if (result.IsModifiedCountAvailable && result.ModifiedCount == 1)
            {
                return true;
            }
            return false;
        }

        ...
    }
}

実行

/Users/Edit/[ObjectId]にアクセス。
f:id:sh_yoshida:20160915134020p:plain

次回は画面からデータの削除です☆彡