How to check against a database for a specific entry using entity framework

不问归期 提交于 2019-12-11 07:39:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!