Pedro Lopes Pedro Lopes - 2 years ago 56
ASP.NET (C#) Question

Linq not being recognized parse in query

I am trying to make a login page. When I try to receive the userdata with linq I get an exception because I try to use Parse in my query. I searched a bit online and found out it is because Linq doesn't recognize Parse. From what I understand I have to translate the not recognisable code to code that linq/slq recognises. Since I have just started using linq queries I have no idea how to accomplish this.

My query:

public static UserDetails GetUser(UserDetails userde)
{
var usr = from u in db.Users
join r in db.Roles on u.RoleId equals r.IdRole
where u.Email == userde.Email && u.Active == true

select new UserDetails
{ Firstname = u.Firstname,
Surname = u.Surname,
Email = u.Email,
Function = u.Function,
Password = u.Password,
Salt = u.Salt,
Userroles = (UserRoles)Enum.Parse(typeof(UserRoles), r.Role1)
};

return usr.FirstOrDefault();
}


I checked these articles:


Answer Source

you should first use FirstOrDefault() and parse it later. Otherwise linq is still trying to build the select-statement. After FirstOrDefault (or ToList,...) you have your result and can then parse it without problems.

Should be something like this:

public static UserDetails GetUser(UserDetails userde)
{
    var usr = from u in db.Users
              join r in db.Roles on u.RoleId equals r.IdRole
              where u.Email == userde.Email && u.Active == true

              select new UserDetails { Firstname = u.Firstname,
                  Surname = u.Surname,
                  Email = u.Email,
                  Function = u.Function,
                  Password = u.Password,
                  Salt = u.Salt,

                  // store the database-value in another property
                  UserrolesUnparsed = r.Role1
                  };

    // get the database-results
    UserDetails details = usr.FirstOrDefault();

    // parse the database-value and set it to the property you want to
    details.Userroles = (UserRoles)Enum.Parse(typeof(UserRoles), details.UserrolesUnparsed);

    return details;

}

sure, there are better/cleaner methods, but this is just to explain you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download