【问题标题】:Seed method doesn't seed播种方法不播种
【发布时间】:2017-03-23 06:11:46
【问题描述】:

我的种子方法没有显示任何错误,但在我从 PMC 运行 update-database 后它肯定不会播种任何内容。由于数据库的整体结构和 Identity 的使用,我的问题非常具体。到目前为止,Seed 方法是这样的:

protected override void Seed(ApplicationDbContext context)
    {
        if (!context.Users.Any())
        {
            var userStore = new UserStore<ApplicationUser>(context);
            var userManager = new UserManager<ApplicationUser>(userStore);
            var user = new ApplicationUser()
            {

                FirstName = "Prvi",
                LastName = "Doktor",
                DateOfBirth = new DateTime(1977, 4, 3),
                EmploymentStatus = EmploymentStatus.Employed,
                PhoneNumber = "062/062-062",
                Email = "prvi@gmail.ocami",
                Address = "Kulovica 9",
                DateCreated = DateTime.Now,
                EmailConfirmed = true,

            };
            userManager.Create(user, "P@ssw0rd");
            context.SaveChanges();
        }
}

我的 ApplicationDbContext 类:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{

    public DbSet<Dentist> Dentists { get; set; }
    public DbSet<Patient> Patients { get; set; }
}

我的模型从 ApplicationUser 扩展而来,而后者又从 IdentityUser 扩展而来

应用用户:

public class ApplicationUser : IdentityUser, IModificationHistory
{
    [Required]
    [Display(Name = "First Name")]
    [StringLength(50)]
    public string FirstName { get; set; }

    [Required]
    [Display(Name = "Last Name")]
    [StringLength(50)]
    public string LastName { get; set; }

    [Required]
    [DataType(DataType.Password)] //DataType is very powerfull Data Annotation, which can affect our view if we use EF, so I will try to accomplish as much as possible with that
    [Display(Name = "Password")]
    public string Password { get; set; }


    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    [Display(Name = "Date of birth")]
    public DateTime DateOfBirth { get; set; }

    [Display(Name = "Address")]
    public string Address { get; set; }

    public EmploymentStatus? EmploymentStatus { get; set; } //This value is nullable

    public DateTime DateCreated { get; set; }
    public DateTime? DateModified { get; set; }


    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here

        return userIdentity;
    }


}

牙医:

[Table("Dentist")]
public class Dentist : ApplicationUser
{

    public string Place { get; set; }


    //Relations
    public virtual ICollection<Patient> Patients { get; set; }
    public virtual Schedule Schedule { get; set; }
}

患者:

[Table("Patient")]
public class Patient : ApplicationUser
{
    //Relations
    public virtual Dentist Dentist { get; set; }

    public virtual MedicalHistory MedicalHistory { get; set; }
    public virtual ICollection<Appointment> Appointments { get; set; }
}

我想知道,为什么它没有给出任何结果,我应该如何看待我建立的这种关系,或者是否可以建立任何其他更合乎逻辑的关系。

【问题讨论】:

  • “但它肯定不会播种任何东西”是什么意思?你是怎么衡量的?
  • Seed 方法只能使用 Update-Database 命令运行。 (如果您没有创建自定义数据库初始化程序)
  • @ThomasWeller 我检查了数据库,那里没有任何数据,有没有其他方法可以推荐。
  • @NicolasZawada 我编辑了问题(运行更新数据库后),抱歉没有更具体
  • 如果要调试 Seed 方法,可以按照以下步骤操作:打开另一个 Visual Studio 实例,将调试器附加到另一个 Visual Studio,设置断点并运行 Update-Database。这可能会对我们有所帮助或提供更多信息

标签: c# asp.net asp.net-mvc entity-framework asp.net-identity


【解决方案1】:

我通常使用这种方法:

  1. 在我的系统中使用我想要的密码从注册屏幕创建一个用户(或使用 passwordhaser 类,链接如下)
  2. 在db中查找用户
  3. 使用这些值更新 Seed 方法。

这样我不会在 Seed 方法中使用任何依赖项,因为该方法将在每次迁移时运行,并且可能需要一些时间才能完成。

Seed 方法应该使用AddOrUpdate 方法:

protected override void Seed(BookService.Models.BookServiceContext context)
{
    context.Users.AddOrUpdate(x => x.Id,
    new ApplicationUser () { Id = 1, FirstName = "FirstName", LastName="LastName", PasswordHash="<hash from dbase>" }
    );       
}

要为密码生成哈希,您还可以使用PasswordHasher.HashPassword 方法。

这样 EF 知道何时添加或更新您在 Seed 方法中提供的值。

if (!context.Users.Any()) 仅在该表中没有记录时才能在新数据库上工作。

【讨论】:

    猜你喜欢
    • 2014-09-05
    • 2022-11-27
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 2015-04-13
    相关资源
    最近更新 更多