如何检查针对数据库的特定条目使用实体框架 [英] How to check against a database for a specific entry using entity framework

查看:110
本文介绍了如何检查针对数据库的特定条目使用实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个登录屏幕,在这里我得到。如何做我使用实体框架的形式向用户ID和密码检查是否有重复的ID在数据库中已存在?

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 ?

我使用实体框架4和asp.net 4.0

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.

谢谢!

推荐答案

复制ID?所以,你要验证的登录是正确的还是要检查创建新用户期间登录已经存在?

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

此调用将返回null如果与通过用户名的用户不存在。

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.

这篇关于如何检查针对数据库的特定条目使用实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆