Home > front end >  The entity type List requires a primary key to be defined
The entity type List requires a primary key to be defined

Time:04-18

I'm using .net 5 and entity framework as ORM. I want to use code first database approach. I have 2 entity classes:

public class PurnchaseOrderItem
{
    public int Id { get; set; }
    public string Name { get; set; }
    public double Price { get; set; }

    [ForeignKey("PurnchaseOrder")]
    public int PurnchaseOrderId { get; set; }
    public PurnchaseOrder PurnchaseOrder { get; set; }
}

public class PurnchaseOrder
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime  CreationDate { get; set; }
    public List<PurnchaseOrderItem> PurnchaseOrderItems { get; set; }

    [NotMapped]
    public double TotalPrice
    {
        get
        {
            return PurnchaseOrderItems.Sum(x => x.Price);
        }
    }
}

But when I try to add new migration, I get the error like the below:

The entity type 'List<PurnchaseOrderItem>' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'. For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943.

Also my db context class:

public class ItemsAppDbContext : DbContext
{
    public ItemsAppDbContext(DbContextOptions options) : base(options)
    {
    }

    public DbSet<AppUser> Users { get; set; }
    public DbSet<PurnchaseOrderItem> PurnchaseOrderItems { get; set; }
    public DbSet<PurnchaseOrder> PurnchaseOrders { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<PurnchaseOrder>()
        .HasOne(p => p.PurnchaseOrderItems)
        .WithMany()
        .OnDelete(DeleteBehavior.Cascade);
    }
}

CodePudding user response:

Update below code in your ItemsAppDbContext

 protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<PurnchaseOrder>()
            .HasMany(p => p.PurnchaseOrderItems)
            .WithOne(g => g.PurnchaseOrder).HasForeignKey(s=>s.PurnchaseOrderId)
            .OnDelete(DeleteBehavior.Cascade);
        }

Read this to know more

  • Related