对于我的身份验证模型,我想确保同一电子邮件不能被多次注册。我对nHibernate和部分LINQ都是新手,所以我问这是否足够进行“检查”以确保发生这种情况。
public MembershipCreateStatus CreateUser(string email, string password)
{
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
var members = session.CreateCriteria<Member>().List<Member>();
// determine is the email address already exists in the database
if (members.Any(i => i.Email == email))
return MembershipCreateStatus.DuplicateEmail;
// create the new member, if they are valid
var member = new Member { Email = email };
session.SaveOrUpdate(member);
transaction.Commit();
}
}
return MembershipCreateStatus.Success;
}
有没有更聪明的方式来做到这一点?过去,我在以前的程序中遇到了麻烦(我在该程序上使用Linq to SQL),所以这次我想获得一些专家建议。
请您参考如下方法:
如约翰所说,创建一个唯一的约束。您可以从以下问题中找出解决方法:
SQL Server 2005 How Create a Unique Constraint?
这样可以确保不会发生重复。
