这是实体框架迁移的配置文件(种子方法)的代码。 通过此代码,我为AspnetUsers表创建了一个用户和角色,并将用户置于名为Admin的角色中。
AppUserManager userMgr = new AppUserManager(new UserStore<AppUser>(context));
AppRoleManager roleMgr = new AppRoleManager(new RoleStore<AppRole>(context));
string roleName = "Admin";
string userName = "admin@educationboard.com";
string password = "Sifre";
string email = "admin@educationboard.com";
if (!roleMgr.RoleExists(roleName))
{
roleMgr.Create(new AppRole(roleName));
}
AppUser user = userMgr.FindByName(userName);
if (user == null)
{
userMgr.Create(new AppUser { UserName = userName, Email = email },
password);
user = userMgr.FindByName(userName);
}
if (!userMgr.IsInRole(user.Id, roleName))
{
userMgr.AddToRole(user.Id, roleName);
}
foreach (AppUser dbUser in userMgr.Users)
{
dbUser.Cinsiyet = eCinsiyetler.Erkek;
}
context.SaveChanges();
然后我还创建了一个名为Articles的实体,每篇文章都有一个作者ID。我在Article实体中将AuthorId命名为UserId。我怎样才能获得并使用我刚刚在下面的代码中创建的UserId?
var articles= new List<Article>
{
new Article{Title="Title 1", AddedDate=DateTime.Now, Content="content here.", UserId=.(What code should be here? };
articles.ForEach(p => context.Articles.AddOrUpdate(s => s.Title, p));
context.SaveChanges();
答案 0 :(得分:1)
为什么不能像上面那样查询用户?
AppUser user = userMgr.FindByName(userName);
if (user == null)
{
userMgr.Create(new AppUser { UserName = userName, Email = email },
password);
user = userMgr.FindByName(userName);
}
然后有user.Id?
如果您在ApplicationDbContext中有句柄,则可以轻松执行类似
的操作ApplicationDbContext db = new ApplicationDbContext();
var user = db.AspNetUser.Single(x => x.UserName == username);
var id = user.Id;