Best method for determining if a row exists

2019-09-05 17:21发布

I am using SQL Server and WebMatrix Razor syntax to try and determine is a username is contained within a table called Users.

The logic I wish to have is :

 bool usernameExists = db.QueryValue("SELECT Username from Users where Username = ?", username);
 if(usernameExists.IsEmpty()){ //username is not in table
    Response.Redirect("Register.cshtml");
 }

What is the best practice for going about this?

2条回答
仙女界的扛把子
2楼-- · 2019-09-05 17:56

One approach would be to implement a custom membership provider which authenticates against your own user table. You application is then decoupled from the specifics of user storage and it's a well understood model for user authentication in ASP.NET applications.

查看更多
虎瘦雄心在
3楼-- · 2019-09-05 18:15

Simplest is probably:

bool usernameExists = db.QueryValue("SELECT usernameExists = CASE WHEN EXISTS 
 (SELECT 1 FROM Users WHERE Username = ?) THEN 1 ELSE 0 END", username);

if (!usernameExists) { Response.Redirect("Register.cshtml"); }

Though I'm speaking strictly from the SQL Server side. I don't know if this is the best approach from the C# side.

查看更多
登录 后发表回答