简体   繁体   English

实体框架将实体对象映射到现有表AspNetUsers

[英]Entity Framework map entity object to existing table AspNetUsers

I use the following class. 我使用以下课程。

public class User
{
      public string FirstName { get; set; }

      public string SecondName { get; set; }
}

In model builder I want to map this object to existing table AspNetUsers. 在模型构建器中,我想将此对象映射到现有表AspNetUsers。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<User>().ToTable("AspNetUsers");

}

I don't want to remove existing table to remain default fields for AspNetUsers. 我不想删除现有表以保留AspNetUsers的默认字段。 In class User I don't want to inherit by IdentityUser in order not to display properties for IdentityUser. 在User类中,我不想由IdentityUser继承,以便不显示IdentityUser的属性。 Is there any way to migrate explicit this entity User to table AspNetUsers without necessity removing existing table ? 有什么方法可以将此实体用户显式迁移到表AspNetUsers,而不必删除现有表?

In Application_Start method of your global.asax file: 在您的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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM