Reputation: 135
this is the select list in the action controller,
ViewBag.UserName = new SelectList(db.Users.Where(g => g.UserName == User.Identity.GetUserName()), "UserName", "UserName");
which I am passing to the view :
<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>
and it's not working erro:
LINQ to Entities does not recognize the method 'System.String GetUserName(System.Security.Principal.IIdentity)' method, and this method cannot be translated into a store expression.
Upvotes: 1
Views: 5151
Reputation: 4456
Change the first line to:
string userName = User.Identity.GetUserName();
ViewBag.UserName = new SelectList(db.Users.Where(g => g.UserName == userName).ToList(), "UserName", "UserName");
You have to add the ToList()
after the Where
in order to execute the query and return the results.
Upvotes: 1
Reputation: 7598
linq/lambda expressions do not recognize the GetUserName
function,
you have to read it in separate variable and use that variable in linq query/lambda expression.
var username = User.Identity.GetUserName();
ViewBag.UserName = new SelectList(db.Users.Where(g => g.UserName == username), "UserName", "UserName");
Upvotes: 2
Reputation: 799
GetUserName can't be translated into a expression. Try it like this
var username = User.Identity.GetUserName();
ViewBag.UserName = new SelectList(db.Users.Where(g => g.UserName == username), "UserName", "UserName");
And maybe adding .ToList() like Haitham suggested.
Upvotes: 3