问题
I am creating a login screen where I get the user Id and password from the form .How do I use the entity framework to check if a duplicate id already exists in the database ?
I am using entity framework 4 and asp.net 4.0
I am really new to the entity framework so a simple response would be very helpful.
Thanks !
回答1:
Duplicate id? So do you want to validate that login is correct or do you want to check that login already exists during creating a new user?
If you want to validate login use:
bool exists = context.Users.Any(u => u.Login == userName && u.Password == pwdHash);
If you need to retrieve user to make validation on the client (which is absolutely not needed) you can just call:
var user = context.Users.SingleOrDefault(u => u.Login == userName);
This call will return null if user with passed user name doesn't exist.
If you want to check that login is free during new user registration you can generally use Any as well but you must do the check and insert in the same serialized transaction - that can have performance impact in high traffic database. The other approach is placing unique constraint on the user name in the database and simply try to save a new user. If the user name exist you will catch the exception.
来源:https://stackoverflow.com/questions/5940027/how-to-check-against-a-database-for-a-specific-entry-using-entity-framework