将自定义索引添加到从User继承的实体,该实体从EF中的IdentityUser继承

时间:2018-11-08 06:49:32

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

我正在使用用户身份制作ASP.NET MVC项目。现在,我的User类继承自IdentityUser:

  [Table("Users")]
public class User : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Patronymic { get; set; } // Отчество
    public string Avatar { get; set; }
    public DateTime? DateOfBirth { get; set; } // Дата рождения
    public DateTime? RegisterDate { get; set; } // Actualy it is a dateTime :)
    public bool? Sex { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> 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;
    }
}

然后我制作了Doctor类,该类继承自它:

  [Table("Doctors")]
public class Doctor : User
{
    [Key]
    public int DoctorId { get; set; }
    public string CurriculumVitae { get; set; }
}

如您所见,我已经添加了自定义索引字段DoctorId。 但是 UserManager无法创建实体 所以问题是我如何添加自定义INT ID索引?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案!要强制实体创建密钥,我们需要添加以下内容:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int DoctorId { get; set; }

代替此

[Key]
public int DoctorId { get; set; }

但这不是最佳解决方案。此外,不要继承用户类以实现角色!