[英]Primary key of AspNetUsers as foreign of another table
I am designing a employee table where I want primary Key of AspNetUsers to be the foreign key ie the Id
Column. 我正在设计一个员工表,我希望AspNetUsers的主键是外键,即Id
列。 How do I do this? 我该怎么做呢? So far I have tried this. 到目前为止,我已经尝试过了。 Don't know if this right or wrong. 不知道这是对还是错。 Any help would be appreciated. 任何帮助,将不胜感激。
[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; }
You don't need to have both UserId
and AppUser
properties on your entity. 您不需要在实体上同时具有UserId
和AppUser
属性。
All you need is the AppUser
property and in your DbContext
you can specify the mapping as follow: 您只需要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
}
}
Note 1 : in fact, you should avoid having both properties, because you could end up with data integrity issue (by this I mean you will need to ensure UserId and AppUser.UserId are always the same). 注1 :事实上,你应该避免使用这两个属性,因为你最终可能会遇到数据完整性问题(我的意思是你需要确保UserId和AppUser.UserId始终相同)。
Note 2 : make sure your user Id is a int
and not a string
for better performance. 注意2 :确保您的用户ID是int
而不是string
以获得更好的性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.