这是动作控制器中的选择列表
ViewBag.UserName = new SelectList(db.Users.Where(g => g.UserName == User.Identity.GetUserName()), "UserName", "UserName");
我传递给观点:
<div class="form-group">
@Html.LabelFor(model => model.UserName, "UserName", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("UserName", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
</div>
</div>
它并没有正常工作:
LINQ to Entities无法识别方法'System.String GetUserName(System.Security.Principal.IIdentity)'方法,这个 方法无法转换为商店表达式。
答案 0 :(得分:3)
GetUserName无法转换为表达式。试试这个
var username = User.Identity.GetUserName();
ViewBag.UserName = new SelectList(db.Users.Where(g => g.UserName == username), "UserName", "UserName");
也许像Haitham建议的那样添加.ToList()。
答案 1 :(得分:2)
linq / lambda表达式无法识别GetUserName
函数,
你必须在单独的变量中读取它并在linq查询/ lambda表达式中使用该变量。
var username = User.Identity.GetUserName();
ViewBag.UserName = new SelectList(db.Users.Where(g => g.UserName == username), "UserName", "UserName");
答案 2 :(得分:1)
将第一行更改为:
string userName = User.Identity.GetUserName();
ViewBag.UserName = new SelectList(db.Users.Where(g => g.UserName == userName).ToList(), "UserName", "UserName");
您必须在ToList()
之后添加Where
才能执行查询并返回结果。