0

I have written some dirty code that retrieves user email in MVC. As you can see I´m using linq queries to retrieve info from my user database.

 List<string> emails = new List<string> {ConstantHelper.AdminEmail, ConstantHelper.OwnerEmail};
 DataContext mDataContext = new DataContext();
 User user = 
      (from allUsers in mDataContext.Users.Where(u => u.UserName == User.Identity.Name) 
        select allUsers).FirstOrDefault();
 string userEmail =
      (from allMemberships in mDataContext.Memberships.Where(u => user != null && u.UserId == user.UserId)
        select allMemberships.Email).FirstOrDefault();
 if(userEmail == null)
 {
     return false;
 }
 emails.Add(userEmail);

 //TODO: senda email

What I want to know if there is any other "shorter" or cleaner way to retrieve user email (of the user who is currently logged in)?

I googled this and found some suggestions regarding this code but I never got that to work for me.

MembershipUser u = Membership.GetUser(username);

My code works, it´s just that I would rather have cleaner code with this, any suggestions would be well appreciated :)

gardarvalur
  • 1,565
  • 9
  • 39
  • 65

1 Answers1

1

MembershipUser u = Membership.GetUser(username); is definitely a much better and shorter way to achieve that. You just need to write a custom membership provider to replace the default one in order to be able to customize the behavior of the GetUser and other methods to suit your needs.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • thanx for the help. It´s a good idea to write my own custom membership provider, I think I´ll have a go with that :) – gardarvalur Jul 26 '12 at 16:02