Reputation: 1297
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!
Upvotes: 1
Views: 757
Reputation: 118957
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();
Upvotes: 1