ASP标识表列更改,但新列名称无法进行映射

时间:2014-06-29 10:47:52

标签: c# entity-framework entity-framework-6 asp.net-identity

我更改了asp标识,以便在Id表的数据库AspNetIdentity列中UserId

modelBuilder.Entity<ApplicationUser>()
                        .Property(p => p.Id)
                        .HasColumnName("UserId");

这很好用。生成的表格为UserId而不是Id 现在,我有另一个表格,应该AspNetUsers UserIdpublic 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; }

数据库中的表格如下:
enter image description here
如果我这样写:

UserId

数据库看起来像:
enter image description here


第一个选项创建了FK字段,但不是FK,而是将新字段添加为JobApply
如何正确映射此列表以使表UserId的字段FKAspNetUsersbase.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; }

    }

表格关系如下:
enter image description here
这是两个类:

{{1}}

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"));