Kelly Soares

Kelly Soares

  • NA
  • 43
  • 11k

The entity type 'IdentityUserLogin<string>' requires a primary key.

Sep 6 2022 12:03 AM

Hi!

I'm trying to implement individual authentication feature in my project. When inheriting the DbContext class, the project reflects migration changes to the database normally. But when I change to IdentityDbContext, Visual Studio returns the following error:

The entity type 'IdentityUserLogin' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'.

How to fix this problem? Here's my code below:

using CleanArch.Domain.Entities;
using CleanArch.Infra.Data.EntityConfigurations;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace CleanArch.Infra.Data.Context
{
    public class ApplicationDbContext : IdentityDbContext
    //public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions options)
            : base(options)
        {
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            //if (!optionsBuilder.IsConfigured)
            //{

            //}
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity()
                .HasMany(p => p.Products)
                    .WithOne(c => c.Category)
                        .HasForeignKey(p => p.IdCategory);

            builder.Entity()
                .HasMany(d => d.OrderDetails)
                    .WithOne(p => p.Product)
                        .HasForeignKey(d => d.ProductId);

            builder.Entity()
                .HasKey(od => new { od.OrderDetailId, od.ProductId });

            builder.Entity()
                .HasMany(d => d.OrderDetails)
                    .WithOne(o => o.Order)
                        .HasForeignKey(d => d.OrderId);

            builder.Entity()
                .HasMany(o => o.Orders)
                    .WithOne(c => c.Client)
                        .HasForeignKey(o => o.ClientId);

            builder.ApplyConfiguration(new ProductConfigurations());
            builder.ApplyConfiguration(new CategoryConfigurations());
            builder.ApplyConfiguration(new OrderConfigurations());
            builder.ApplyConfiguration(new OrderDetailConfigurations());
            builder.ApplyConfiguration(new ClientConfigurations());

            //base.OnModelCreating(builder);
            //ModelBuilder builder.ApplyConfiguration(new ProductConfiguration());
        }

        public DbSet Products { get; set; }
        public DbSet Categorys { get; set; }
        public DbSet Clients { get; set; }
        public DbSet Orders { get; set; }
        public DbSet OrderDetails { get; set; }
    }
}


Answers (2)