简体   繁体   中英

Thoroughly Check to see if an Email Exists, NHibernate, LINQ

For my authentication model, I want to make sure that it is impossible for the same email to be registered more than once. I am new to both nHibernate and partially LINQ, so I am asking if this is adequate enough of a 'check' to ensure that happens.

  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;
  }

Is there a more intelligent way of accomplishing this? I've had trouble with this in the past with a previous program (I used Linq to SQL on that one), and so I wanted to get some expert advice, this time around.

What you're doing there is loading ALL members and querying the collection in memory.

This executes the query in the DB:

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

Create a unique constraint as John said. You can figure out how to do that from this question:

SQL Server 2005 How Create a Unique Constraint?

That will ensure a duplicate never occurs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM