我构建了一个查询以通过用户名查找用户。当我运行该程序,我得到:序列包含多个元素异常,但在数据库中只有一个
出现InvalidOperationException:序列包含多个元素
我检查测试数据库,只有4位用户,没有双名有。异常来自哪里?以下是查询:
public void setUser(String userName)
{
AzaraUser = DatabaseConnection.DataContext.GetTable<AzaraUser>()
.SingleOrDefault(a => a.ProgramUserName == userName || a.UserName == userName);
}
随着下面的提示,我尝试调试,发现该方法成为一个空字符串。因此,在这种情况下,我得到几个响应是正常的,因为ProgramUserName只有几行不是空的,因为它是针对使用活动目录帐户登录的用户。
但为什么我会得到这个空字符串?难道那个时候WebSecurity也是空的?它会在哪一点获得有关当前用户的信息?
这是我的日志中的方法:
[HttpPost]
public ActionResult Login(FormCollection logInForm)
{
// try the default membership auth
if (Membership.ValidateUser(logInForm["name"], logInForm["password"]))
{
FormsAuthentication.SetAuthCookie(logInForm["name"], false);
user.setUser(WebSecurity.CurrentUserName);
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null)
{
Response.Redirect("~/home/index");
}
else
{
Response.Redirect(returnUrl);
}
}
else
{
ModelState.AddModelError("", "Login failed");
}
// try to auth user via AD
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
{
if (pc.ValidateCredentials(logInForm["name"], logInForm["password"]))
{
FormsAuthentication.SetAuthCookie(logInForm["name"], false);
user.setUser(WebSecurity.CurrentUserName);
return RedirectToAction("Index", "Home");
}
}
return View("LogOn");
}
尝试将SingleOrDefault更改为Where并将ToList添加到最后,然后在下一行放置一个断点,以便可以看到返回的实际行。该错误是相当明确的... –
你是什么意思的“该方法变成一个空字符串”?你能发布你得到的输出吗? _(不是记录中的所有内容,但至少是UserName和ProgramUserName)_ –
WebSecurity.CurrentUserName给setUser指定字符串“”。这是在数据库中搜索。数据库中有4条记录。只有一个具有ProgramUserName,所有其他记录在该行中都为空。我现在用解决方法解决了问题,所以程序正在运行,但我想知道WebSecurety在哪个时间获取用户的用户名。 –