I am designing a employee table where I want primary Key of AspNetUsers to be the foreign key ie the Id
Column. 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.
All you need is the AppUser
property and in your DbContext
you can specify the mapping as follow:
[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).
Note 2 : make sure your user Id is a int
and not a string
for better performance.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.