简体   繁体   中英

Where clause with Linq in C# MVC 4

I'm trying to select a field that is from my UserProfile table, RoleID. The parameter passed into this Post method is Username and it is a string from a textbox which is working correctly.

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult GetRoles(string UserName)
    {
        if (!string.IsNullOrWhiteSpace(UserName))
        {
             string applyfor = db.Profiles
               .Select(s => s.RoleID)
               .Where(a=>Profile.UserName.Contains(UserName))
               .First();
             ViewBag.ApplyingFor = applyfor;

However this gives me Sequence contains no elements.

I've tried several other methods, such as .Equals() . I'm pretty sure it is my where clause.

What am I doing wrong here?

Note: RoleID is not part of the Websecurity , also there is data in the database.

If you break down your code and highlight what each Lambda statement returns you'd see the issue:

string applyfor = db.Profiles
                     ^^^^^^^^

This most likely returns something like DbSet<Profile> .

  .Select(s => s.RoleID)
   ^^^^^^

This most likely returns IQueryable<int> . At this point you've lost the context of the profile and now only have zero or more RoleID s.

So your a in the where statement is an int Value, you have no way to find a username now, and this where statement literally makes no sense.

  .Where(a=>Profile.UserName.Contains(UserName))

When you rearrange the Lambda expressions as Grant Winney's Answer shows you can see why most of the time a Select() is the last thing that normally happens (in simple queries).

I would wager there is no UserName on Profile . and you want to

string applyfor = db.Profiles
                    .Where(p => p.User.Any(u.UserName == UserName))
                    .Select(p => p.RoleID)
                    .First();

As a side note, Microsoft Best practice is to Camel-Case method parameters . So I would recommend your method look like:

public ActionResult GetRoles(string userName) // or username
{
}

您的Where语句应该看起来更像这样:

 ... .Where(a => a.UserName == Profile.UserName).FirstOrDefault();

Try this instead:

string applyfor = db.Profiles
                    .Where(x => x.UserName == UserName)
                    .Select(x => x.RoleID)
                    .First();

Also, if there's a chance you won't find a matching record, use FirstOrDefault() instead of .First() and then test for null .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM