问题描述
我已更改 asp 身份,以便在 AspNetIdentity
表的数据库 Id
列中为 UserId
:
I have changed the asp Identity so that in database Id
column of AspNetIdentity
table be UserId
:
modelBuilder.Entity<ApplicationUser>()
.Property(p => p.Id)
.HasColumnName("UserId");
而且效果很好.生成的表有 UserId
而不是 Id
.
现在我有另一个表,应该由 UserId
与 AspNetUsers
映射:
这样写的时候:
And that works fine. Generated table have UserId
instead Id
.
Now I have another table that should be mapped with AspNetUsers
by UserId
:
When write it this way:
public class JobApply
{ ...
public int UserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
数据库中的表如下:
如果我这样写:
Table in database looks like:
And if I write it like this:
public class JobApply
{ ...
public int ApplicationUserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
数据库如下:
第一个选项创建了 UserId
字段,但它不是 FK
而不是将新字段添加为 FK
.
我怎样才能正确地将其映射到具有字段 UserId
的表 JobApply
为 FK
到 AspNetUsers
?
更新
当我添加这个时:
database looks like:
First option created UserId
field but it is not FK
instead of that new field is added as FK
.
How can I properly map this to have table JobApply
with field UserId
to be FK
to AspNetUsers
?
UPDATE
When I add this:
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>()
.Property(p => p.Id)
.HasColumnName("UserId");
modelBuilder.Entity<JobApply>()
.HasRequired(e => e.ApplicationUser)
.WithMany()
.HasForeignKey(e => e.UserId);
表关系如下:
这是两个类:
Tables relation looks like this:
This is both classes:
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; }
}
推荐答案
像这样定义你与 fluent API 的关系:
Define your relationship with the fluent API like this:
modelBuilder.Entity<JobApply>()
.HasRequired(e => e.ApplicationUser)
.WithMany(e => e.JobApplies)
.HasForeignKey(e => e.UserId);
您也可以从 ApplicationUser
类中删除属性 UserId
,然后像这样定义映射:
You may as well remove the property UserId
from the ApplicationUser
class and then define the mapping like this:
modelBuilder.Entity<JobApply>()
.HasRequired(e => e.ApplicationUser)
.WithMany(e => e.JobApplies)
.Map(m => m.MapKey("UserId"));
这篇关于ASP 标识表列更改,但无法使用新列名进行映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!