首页 文章

无法在.NET中的实体框架代码第一种方法中迁移AspNetUser实体

提问于
浏览
0

我正在使用Visual Studio 2013开发ASP.NET MVC项目 . 我正在使用Entity Framework Code First Approach与数据库进行交互 . 但由于ASP.NET中内置的身份系统,我在迁移数据方面遇到了问题 . 在触摸身份系统之前,一切都很好 .

这些是我所做的步骤 .

  • 我使用内置身份系统从UI注册了一个帐户 . 所以AspNetUsers表是在数据库中创建的 .

  • 我为我的代码创建了AspNetUser类,因为我需要使用它 .

  • 然后我运行迁移并更新数据库命令 . 它抛出错误 .

这是我的AspNetUser类

public class AspNetUser
    {
        [Required]
        public String Id { get; set; }
        [Required]
        public String UserName { get; set; }
        public String PasswordHash { get; set; }
        public String SecurityStamp { get; set; }
        [Required]
        public String Discriminator { get; set; }
    }

这是我的db上下文类

public class AyarDbContext : DbContext
    {
        public AyarDbContext()
            : base("DefaultConnection")
        {

        }

        public DbSet<Category> Categories { get; set; }
        public DbSet<Region> Regions { get; set; }
        public DbSet<Area> Areas { get; set; }
        public DbSet<Item> Items { get; set; }
        public DbSet<ItemContactInfo> ItemContacts { get; set; }
        public DbSet<Gallery> Galleries { get; set; }
        public DbSet<Mail> Mails { get; set; }
        public DbSet<AspNetUser> AspNetUsers { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

        }
    }

这是我得到的错误 .

数据库中已存在名为“AspNetUsers”的对象 .

如何迁移AspNetUser类?我使用UI注册,因为我自动创建其他表需要身份系统 . 如何使用已存在于数据库中的AspNetUsers表迁移该类并进行映射 .

1 回答

  • 0

    正如错误所解释的那样,该表已经存在并且可以通过以下方式访问:

    var user = context.Users.First(u => u.Id == myId);
    

    如果要扩展用户类并添加属性,可以继承它:

    public class MyAppUser : IdentityUser
    {
        // don't include properties already in IdentityUser
        public string MyNewProperty { get; set; }
    }
    

    http://johnatten.com/2014/06/22/asp-net-identity-2-0-customizing-users-and-roles/

相关问题