AspNetUsers的主键作为另一个表的外来

时间:2015-03-04 08:12:18

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

我正在设计一个员工表,我希望AspNetUsers的主键是外键,即Id列。我该怎么做呢?到目前为止,我已经尝试过了。不知道这是对还是错。任何帮助,将不胜感激。

[Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int HumanResourceId { get; set; } 

    //foreign key of userid
    public string UserId { get; set; }
    [ForeignKey("UserId")]
    public virtual ApplicationUser appuser { get; set; }

    [Required, MaxLength(30),Index]
    public string FirstName { get; set; }

    public string MiddleName { get; set; }

    [Required, MaxLength(25)]
    public string LastName { get; set; }

    [Required, MaxLength(10), Index(IsUnique = true)]
    public string MobileNumber { get; set; }

    [Required, DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    public DateTime? DateOfBirth { get; set; }

    [Required]
    [Column(TypeName = "ntext")]
    public string Address { get; set; }

    [Required]
    public string Gender { get; set; }

    [Required]
    public DateTime? HireDate { get; set; }

    public DateTime? Date_from { get; set; }

    public DateTime? Date_to { get; set; }

    public bool Active { get; set; }

1 个答案:

答案 0 :(得分:0)

您的实体不需要同时具有UserIdAppUser属性。

您需要的只是AppUser属性,在DbContext中,您可以指定映射如下:

[Table("AspNetUsers")] 
public class ApplicationUser
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string Username { get; set; }
}

public class Employee
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int EmployeeId { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public virtual ApplicationUser AppUser { get; set; }
}

public class DbContext : System.Data.Entity.DbContext
{
    public DbContext()
        : base("name=DbContext")
    { }

    public IDbSet<ApplicationUser> Users { get; set; }
    public IDbSet<Employee> Employees { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>()
            .HasRequired(x => x.AppUser)
            .WithMany()
            .Map(m => m.MapKey("UserId")); // Name of you FK column
    }
}

注1 :事实上,你应该避免同时拥有这两个属性,因为你最终可能会遇到数据完整性问题(我的意思是你需要确保UserId和AppUser.UserId始终是相同)。

注2 :确保您的用户ID为int,而不是string,以提高性能。