2

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:

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Pedro Lopes
  • 479
  • 2
  • 9
  • 20

1 Answers1

4

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.

Matthias Burger
  • 5,549
  • 7
  • 49
  • 94
  • I was trying to do this var usr1 = db.Users.Where(u => usr.FirstOrDefault().Email == u.Email).FirstOrDefault(); usr.FirstOrDefault().Userroles = (UserRoles)Enum.Parse(typeof(UserRoles), usr1.Role.Role1); But for some reason my usrroles always sticks to administrator even when it is just a common user. Will try to do what you said – Pedro Lopes Aug 16 '17 at 12:17