Voli
Voli

Reputation: 29

How to remove the duplication of UserId column in ASP.NET identity

In my .NET project, I've created a class "ApplicationUser" which inherits from IdentityUser like this

{
   public class ApplicationUser : IdentityUser
   {
       public ICollection<Task> Tasks { get; set; }
       public ICollection<Category> Categories { get; set; }
   }
} 

and making a one to many relationship with "category" class like this :

namespace ToDo.Models
{
    public class Category
    {
        public int CategoryId { get; set; }
        [Required(ErrorMessage = "Category Name is required.")]
        public string CategoryName { get; set; }
        public string UserId { get; set; }
        public ICollection<Task> Tasks { get; set; }
        public ApplicationUser ApplicationUser { get; set; }
    }
}

But when I'm creating a new category it goes to the database with two columns for the Id's the first is UserId and the second is ApplicationUserId, which I didn't create, could anyone help me please? Thanks in advance. and also Here is an image from the database enter image description here

Upvotes: 0

Views: 204

Answers (1)

Neil W
Neil W

Reputation: 9247

By convention EF will create foreign key as "{NavigationProperty}Id", hence EF is creating ApplicationUserId as your foreign key. It just thinks that UserId is some value that you've added to the class for your own purposes.

You can configure EF to specifically use UserId as the FK for ApplicationUser in Fluent API:

builder.Entity<Category>()
    .HasOne<ApplicationUser>(p => p.ApplicationUser)
    .WithMany()
    .HasForeignKey(p => p.UserId);

or using Annotations:

[ForeignKey("UserId")]
public ApplicationUser ApplicationUser { get; set; }

Upvotes: 1

Related Questions