使用EF Code First控制属性唯一性的最佳方法 [英] Best way to control unicity of an attribute using EF Code First

查看:81
本文介绍了使用EF Code First控制属性唯一性的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个User类,该类的Name属性必须唯一.到目前为止,我已经研究了三种检查方法:

I've got a class User which has an attribute Name that must be unique. So far I've investigated 3 ways of checking this:

  • 注释

[StringLength(100)]
[Index(IsUnique = true)]
public string Name { get; set; }

问题是,通过尝试插入具有重复名称的用户,它抛出了这个ex:如您所见,我将不得不浏览内部异常(我不知道是否可能,但我认为是可能的),而最后一个内部异常的消息根本不是用户友好的.

Problem is, by trying to insert a user with a repeated name it throws this ex: as you can see, I would have to navigate into the inner exceptions (which I don´t know if it is possible, but I assume it is) and the last inner exception´s message is not user friendly at all.

  • Fluent Api

https://stackoverflow.com/a/23155759/5750078

我还没有尝试过,但是我相信它和注解有同样的问题.

I haven´t tried it but I believe it is has the same problem that Annotations.

  • 用手检查

控制器代码:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Name,Password,Profile")] User user)
    {
        if (ModelState.IsValid)
        {
            lock (locker)
            {
                validateNameUnicity();
                db.Users.Add(user);
                db.SaveChanges();
            }
            return RedirectToAction("Index");
        }

        return View(user);
    }

问题:检查取决于我的代码,可能不如基于日期的检查准确.此外,与其他两个选项相比,我需要编程更多的逻辑.最后但并非最不重要的一点是,如果我以某种方式直接访问数据库,将根本不会进行任何检查.

Problem: the check depends on my code, which may not be as accurate as date base checkings. Besides I will need to program more logic than the other two options. And last but no least if somehow I access the database directly there will be no checks at all.

我需要知道哪种方法是最佳的做法,因为我想自己学习,并且我想做的事情尽可能的好.

I need to know which is the best practice to do this, because I'm trying to learn on my own, and I would like to do things as best as possible.

推荐答案

当并发用户设法插入相同的记录时,您实际上应该同时执行两种操作:检入代码作为唯一性保护措施毕竟.(由于支票和实际插入之间的延迟).

You should actually do both, a check in code and a uniqueness index as a final guard when concurrent users manage to insert identical records after all. (Because of the latency between the check and the actual insert).

这意味着您在调用 SaveChanges 时总是必须捕获异常,但这仍然不是一个坏主意.

This means that you always have to catch exceptions when you call SaveChanges, but that's not a bad idea anyway.

对于唯一性检查,您可以使用我在此处中描述的机制,只需更改电子邮件输入 Name ,您就很好了.

For the uniqueness check you could use the mechanism I described here, just change email into Name and you're good to go.

您可以使用此扩展方法从一系列内部异常中挖掘出最后一条异常消息:

You could dig up the last exception message from a chain of inner exceptions by this extension method:

public static string GetDeepestExceptionMessage(this Exception exception)
{
    string msg = string.Empty;
    while (exception != null)
    {
        msg = exception.Message;
        exception = exception.InnerException;
    }
    return msg;
}

这篇关于使用EF Code First控制属性唯一性的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆