彻底检查电子邮件是否存在,NHibernate,LINQ

时间:2010-12-10 21:35:23

标签: c# linq nhibernate

对于我的身份验证模型,我想确保同一封电子邮件不可能多次注册。我是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),所以我想得到一些专家建议,这一次。

2 个答案:

答案 0 :(得分:7)

你正在做的是加载所有成员并在内存中查询集合。

这将在DB中执行查询:

//this of course goes inside the transaction
if session.Query<Member>().Any(i => i.Email == email))
    return MembershipCreateStatus.DuplicateEmail;

答案 1 :(得分:4)

如John所说,创建一个独特的约束。你可以从这个问题中弄清楚如何做到这一点:

SQL Server 2005 How Create a Unique Constraint?

这将确保永远不会发生重复。