使用FirstOrDefault C#mvc4查询区分大小写

时间:2014-10-28 04:10:44

标签: c# asp.net-mvc-4

我正在尝试评估用户和密码,但如果我使用大写或小写,我得到相同的结果,数据库区分大小写,但它一直忽略该配置这是我的代码:

public ActionResult Login(Model.user user){

    bool isValid=false;
    var user= db.users.FirstOrDefault(u=>u.user==user.user && u.password==user.password)
    if(user!=null){
      isValid=true;          
    }
}

我做错了什么?

2 个答案:

答案 0 :(得分:1)

试试这个: -

var query = users.FirstOrDefault(u => u.UserName == user.UserName && String.Compare(u.Password, user.Password,false) == 0);

工作Fiddle

根据OP的问题(基于数据库): -

var query = db.Users.ToList().Where(x => (string.Compare(x.UserName, user.UserName, false) == 0) && (string.Compare(x.Password, user.Password, false) == 0)).FirstOrDefault();

答案 1 :(得分:0)

试试这种方式

var result = from userlist in context.UserMasters
             where userlist.UserName.Equals(username)

// May be better (if usernames are unique):
var result = context.UserMasters.SingleOrDefault(u=>u.UserName == username);

if(result == null){
   // Did not find any user(s)
}

// If you want a case sensitive password check
if(result.UserPassword == pass){
  // The password is correct
}
else
{
      throw new Exception("Invalid password");
}

// If you don't
if(result.UserPassword.Equals(pass, StringComparison.InvariantCulture)){
  // The password is correct
}