1

I have a program where I read a CSV file of email addresses and user data, and bring it into a C# console line application, and write each one into the AspNetUser table (assuming it passes validation).

I can write in a new user via the following code:-

AspNetUser user = new AspNetUser();
user.Id = Guid.NewGuid().ToString();
user.UserName = username;
// More Code
db.AspNetUsers.Add(user);
db.SaveChanges();

How can I from here, assign them to a role, so adding a record in the AspNetUsersRole table? The table is not accessible through LINQ? I don't seem to have access to UserManager or ApplicationUser in the console line application?

Thanks in advance!

2
  • If you are using Identity, you should use the UserManager and RoleManager classes to manage your users/roles. Commented Aug 22, 2016 at 9:37
  • How can I access these from a console application though? Intellisense just offers me to create a new class of the same name? Is it a reference I need to add? Commented Aug 22, 2016 at 9:40

1 Answer 1

1

If you are using Identity, you should use the UserManager and RoleManager classes to manage your users/roles:

var user = new AspNetUser
{ 
    Id = Guid.NewGuid().ToString(),
    UserName = username
};

var userManager = new UserManager<AspNetUser>();
userManager.Create(user, "password");
userManager.AddToRole(user.Id, "RoleName");

But if you really want to stick with your context, then you can use the navigation property of the user:

var user = new AspNetUser
{ 
    Id = Guid.NewGuid().ToString(),
    UserName = username
};

db.AspNetUsers.Add(user);
var role = db.AspNetRoles.Single(r => r.Name = "RoleName");
user.Roles.Add(role);
db.SaveChanges();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.