Why Join
Become a member
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
C# Corner Home
Technologies
MonthlyLeaders
ASK A QUESTION
Forumguidelines
Marius Vasile
1.5k
517
5.5k
asp.net core seed data with startup
Jan 5 2021 7:00 PM
I am trying to seed data at startup in preparation for publishing. I want to have the web admin seeded at startup. What I did is
a class
using
Microsoft.AspNetCore.Identity;
using
Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using
RoSafety.Data;
using
RoSafety.Models;
using
System.Linq;
namespace
RoSafety
{
public
class
RoSafetyDbStartup
{
private
readonly
ApplicationDbContext _context;
public
RoSafetyDbStartup(ApplicationDbContext context)
{
_context = context;
}
public
async
void
SeedAdminUser()
{
var user =
new
UserDataClass
{
UserName =
"weba@admin.com"
,
NormalizedUserName =
"weba@admin.com"
,
Email =
"weba@admin.com"
,
OrgID =
"RS-001"
,
NormalizedEmail =
"weba@admin.com"
,
EmailConfirmed =
true
,
LockoutEnabled =
true
};
var roleStore =
new
RoleStore<UserRoleClass>(_context);
if
(!_context.Roles.Any(r => r.Name ==
"AdminNew"
))
{
await roleStore.CreateAsync(
new
UserRoleClass { Name =
"AdminNew"
, NormalizedName =
"ADMINNEW"
});
}
if
(!_context.Users.Any(u => u.UserName == user.UserName))
{
var password =
new
PasswordHasher<UserDataClass>();
var hashed = password.HashPassword(user,
"vsdrg4gherrhb4re54#RFw"
);
user.PasswordHash = hashed;
var userStore =
new
UserStore<UserDataClass>(_context);
await userStore.CreateAsync(user);
await userStore.AddToRoleAsync(user,
"AdminNew"
);
}
await _context.SaveChangesAsync();
}
}
}
and in statup
public
void
Configure(IApplicationBuilder app, IWebHostEnvironment env, RoSafetyDbStartup dbInit)
{
.................................other data........................
dbInit.SeedAdminUser();
}
but no data is updated in AspNetUsers or AspNetRoles on database-update
Oh, and my Identity is
public
class
UserDataClass : IdentityUser
{
......some data.....
}
public
class
UserRoleClass : IdentityRole
{
public
virtual
ICollection<AppIdentityRole> AppUserRoles {
get
;
set
; }
}
public
class
AppIdentityRole : IdentityUserRole<
string
>
{
public
virtual
UserDataClass User {
get
;
set
; }
public
virtual
UserRoleClass Role {
get
;
set
; }
}
What am I doing wrong?
Reply
Answers (
10
)
shopping cart full website using asp.net mvc 5
Could not fetch windows identity name in web api 2.0