我更改了asp标识,以便在Id
表的数据库AspNetIdentity
列中UserId
:
modelBuilder.Entity<ApplicationUser>()
.Property(p => p.Id)
.HasColumnName("UserId");
这很好用。生成的表格为UserId
而不是Id
现在,我有另一个表格,应该AspNetUsers
UserId
与public class JobApply
{ ...
public int UserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
进行映射
这样写的时候:
public class JobApply
{ ...
public int ApplicationUserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
数据库中的表格如下:
如果我这样写:
UserId
数据库看起来像:
第一个选项创建了FK
字段,但不是FK
,而是将新字段添加为JobApply
。
如何正确映射此列表以使表UserId
的字段FK
为AspNetUsers
到base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>()
.Property(p => p.Id)
.HasColumnName("UserId");
modelBuilder.Entity<JobApply>()
.HasRequired(e => e.ApplicationUser)
.WithMany()
.HasForeignKey(e => e.UserId);
?
的更新
当我添加这个:
public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
public string Email { get; set; }
public string ConfirmationToken { get; set; }
public bool IsConfirmed { get; set; }
public string PasswordResetToken { get; set; }
public int CityId { get; set; }
public virtual City City { get; set; }
public virtual ICollection<JobApply> JobApplies { get; set; }
}
public class JobApply
{
public int JobApplyId { get; set; }
public int UserId { get; set; }
public int JobId { get; set; }
public int JobApplyStatusId { get; set; }
public DateTime CreatedDate { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public virtual Job Job { get; set; }
public virtual JobApplyStatus JobApplyStatus { get; set; }
}
表格关系如下:
这是两个类:
{{1}}
答案 0 :(得分:2)
使用流畅的API定义您的关系,如下所示:
modelBuilder.Entity<JobApply>()
.HasRequired(e => e.ApplicationUser)
.WithMany(e => e.JobApplies)
.HasForeignKey(e => e.UserId);
您也可以从UserId
类中删除属性ApplicationUser
,然后像这样定义映射:
modelBuilder.Entity<JobApply>()
.HasRequired(e => e.ApplicationUser)
.WithMany(e => e.JobApplies)
.Map(m => m.MapKey("UserId"));