RavenDB UniqueConstraint似乎不起作用

时间:2015-12-14 20:00:03

标签: ravendb asp.net-core-mvc

我一直在尝试让UniqueConstraint工作一天,但看起来并非如此。我有一个简单的MVC6站点,在POST上创建User。我希望在第二个POST上应该抛出一个异常,因为用户已经创建了相同的属性。我想确保电子邮件地址是唯一的。

using Raven.Client;
using Raven.Client.Document;
using Raven.Client.UniqueConstraints;

namespace MVC6Test.DomainModel
{
    public class User
    {
        public string Id { get; private set; }
        [UniqueConstraint]
        public string Email { get; set; }
        public string Password { get; set; }
        public string Name { get; set; }
    }
}

namespace MVC6Test.Web.Controllers
{
    public class AdminController : Microsoft.AspNet.Mvc.Controller
    {
        private IDocumentStore _documentStore { get; set; }
        public IDocumentSession Session { get; set; }

        [HttpPost]
        [AllowAnonymous]
        [Route("login")]
        public async Task<IActionResult> Login(string userName, string password)
        {
            User user = new User() {
                Email = "test@gmail.com"
            };

            Session.Store(user);
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (_documentStore.IsDefault()) {
                _documentStore = context.HttpContext.RequestServices.GetRequiredService<IDocumentStore>();
            }
            Session = _documentStore.OpenSession();
            base.OnActionExecuting(context);
        }

        public override void OnActionExecuted(ActionExecutedContext context)
        {
            using (Session) {
                if (Session != null && context.Exception == null) {
                    Session.SaveChanges();
                }
            }
            base.OnActionExecuted(context);
        }
    }
}

namespace MVC6Test.Web
{
    public class Startup
    {
        private IDocumentStore DocumentStore;

        public void ConfigureServices(IServiceCollection services)
        {
            DocumentStore = new DocumentStore {
                DefaultDatabase = "MVC6Test",
                Url = "http://localhost:3366"
            };
            DocumentStore.Listeners.RegisterListener(new UniqueConstraintsStoreListener());
            DocumentStore.Initialize();

            services.TryAddSingleton(typeof(IDocumentStore), (provider) => {
                return DocumentStore;
            });
        }

        public void Configure(IApplicationBuilder app, IApplicationLifetime lifetime)
        {
            lifetime.ApplicationStopped.Register(() => {
                DocumentStore.Dispose();
            });
        }
    }
}

我确实在创建的项目上获得了这些元数据:

{
    "Raven-Entity-Name": "Users",
    "Raven-Clr-Type": "MVC6Test.DomainModel.User, MVC6Test",
    "Ensure-Unique-Constraints": [
        {
            "Name": "Email",
            "CaseInsensitive": false
        }
    ]
}

0 个答案:

没有答案