I am using .Net Identity 2.0 with Entity Framework 6.0. I have a Person
class inheriting IdentityUser
. I have a Teacher
(has additional Title
property) and Student
(has additional StudentNumber
property) class inheriting from the Person
class. I also have their corresponding roles in the database: Student
and Instructor
(or teacher).
I wonder if the code below is the most efficient way of creating users with specific roles, it seems to be a redundant but I could not figure a shorter way:
gEchoLuDBContext _db = new gEchoLuDBContext();
var userStore = new UserStore<IdentityUser>(_db);
var userManager = new UserManager<IdentityUser>(userStore);
foreach (ListItem role in rb_Roles.Items)
{
if (role.Selected)
{
var user = new Person()
{
UserName = txt_Username.Text,
FirstName = txt_Firstname.Text,
LastName = txt_Lastname.Text,
Email = txt_Email.Text
};
if (role.Text == "Student")
{
user = new Student()
{
StudentNumber = " ",
UserName = txt_Username.Text,
FirstName = txt_Firstname.Text,
LastName = txt_Lastname.Text,
Email = txt_Email.Text
};
}
else if (role.Text == "Instructor")
{
user = new Teacher()
{
Title = "",
UserName = txt_Username.Text,
FirstName = txt_Firstname.Text,
LastName = txt_Lastname.Text,
Email = txt_Email.Text
};
}
IdentityResult result = userManager.Create(user, txt_Password.Text);
if (result.Succeeded)
{
IdentityResult result2 = userManager.AddToRole(user.Id, role.Text);
if (!result2.Succeeded)
{
lbl_Result.Text = "The user created successfully. But, the selected roles are not assigned!";
}
}
}
}
1 Answer 1
Well, you say that both Student
and Teacher
inherit from the base class Person
. Considering that, and the fact that you never actually use either the Student or Teacher specifically in this code, why bother checking the Role at all? Your UserManager<IdentityUser>
is taking in a person, not a Teacher
or a Student
.
Now, if I would happen to be wrong about that, I would suggest looking into the Factory Pattern. You could create a factory that takes in all of the fields from your GUI as arguments, and decides which type of Person
to create based on the arguments it's recieved. It won't do away with all of the if...else if
logic, but it will abstract it away and hide it from your GUI and make your code more testable.
-
1\$\begingroup\$ I think he does need to create the Student and Teacher, since EF will assign the data differently based on that relationship (if he's using inheritance with his EF data model). \$\endgroup\$JasonLind– JasonLind2015年03月02日 09:49:13 +00:00Commented Mar 2, 2015 at 9:49
-
\$\begingroup\$ Ahh. Well then, a factory would be in order @JasonLind. \$\endgroup\$RubberDuck– RubberDuck2015年03月02日 10:12:35 +00:00Commented Mar 2, 2015 at 10:12