我使用以下课程。
public class User
{
public string FirstName { get; set; }
public string SecondName { get; set; }
}
在模型构建器中,我想将此对象映射到现有表AspNetUsers。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>().ToTable("AspNetUsers");
}
我不想删除现有表以保留AspNetUsers的默认字段。在类User中,我不希望IdentityUser继承,以便不显示IdentityUser的属性。有没有办法将这个实体User显式迁移到表AspNetUsers而无需删除现有的表?
答案 0 :(得分:0)
在global.asax文件的Application_Start方法中:
using (var db = new DataContext())
using (var userStore = new UserStore<ApplicationUser>(db))
using (var userManager = new UserManager<ApplicationUser>(userStore))
{
foreach (var oldUser in db.OldUsers)
{
var newUser = new IdentityUser
{
UserName = oldUser.UserName,
// set other properties
}
var result = userManager.Create(newUser);
if (!result.Succeeded)
{
// log error
}
}
db.OldUsers.RemoveRange(db.OldUsers);
db.SaveChanges();
}