ASP Identity table column change but mapping is no

2019-03-02 16:59发布

问题:

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

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; }

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; }

    }

回答1:

Define your relationship with the fluent API like this:

modelBuilder.Entity<JobApply>()
                    .HasRequired(e => e.ApplicationUser)
                    .WithMany(e => e.JobApplies)
                    .HasForeignKey(e => e.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"));