I am creating a method to load default users into the identity database that comes with the MVC5 template. I have ended up with a compile error on the line (see full code below)
var user = CreateUser("email@email.email",true);
The exact error is Error 16 A local variable named 'user' cannot be declared in this scope because it would give a different meaning to 'user', which is already used in a 'child' scope to denote something else
I do not understand how this is happening, and what I find equally baffling is a soon as I comment out this line the next line cannot find variable user
. If the compile refuses to let me use user
due to a previous declaration, then how can it fail to find user
after the duplicate declaration is removed.
I think this is related to closure/inline methods holding on to the name but am not sure. I also know I can fix this by just changing the variable name, I am more interested in the why.
Here is a simplified example of the method I am currently writing:
internal static void CreateDefaultUsers(IdentityDb context)
{
var defaultPassword = "admin";
var userManager = new UserManager<User>(new UserStore<User>(context));
var roleManager = new RoleManager<UserRole>(new RoleStore<UserRole>(context));
Func<string, User> CreateUser = (string email) =>
{
User user = context.Users.SingleOrDefault(u => u.UserName == email);
if (user == null)
{
user = new EziOrderUser {
FirstName = email.Substring(0, email.LastIndexOf("@")),
Email = email, UserName = email, EmailConfirmed = true };
userManager.Create(user, defaultPassword);
userManager.AddToRole(user.Id, "User");
}
return user;
};
var user = CreateUser("email@email.email"); // <-- Error here
userManager.AddToRole(user.Id, "Administrator"); // <-- Then here
}
(Have not checked that this sample compiles, it does illustrate the problem however)