ASP标识表列更改,但新列名称不可能进行映射 [英] ASP Identity table column change but mapping is not possible with new column name
问题描述
我已经更改了asp标识,以便在 Id 列
AspNetIdentity
表的数据库 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
。
现在我有另一个应该映射的表与 AspNetUsers
由 UserId
:
以这种方式写:
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
。
如何正确地映射这个表,让表 JobApply
与字段 UserId
FK
to 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; }
}
推荐答案
定义您与流畅的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);
您也可以移除属性 UserId
从 ApplicationUser
类,然后定义如下的映射:
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标识表列更改,但新列名称不可能进行映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!