Entity Framework complains that there is no primary key

vitaminchik 486 Reputation points
2024-07-09T20:27:16.29+00:00

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

namespace WpfApp6.Models;

public partial class Product

[Key]

public int IdProduct { get; set; }

public string NameOfProduct { get; set; } = null!;

public virtual ICollection<Purchase> Purchases { get; set; } = new List<Purchase>();
```}

 internal class ProductRepository : DbContext

 {

```typescript
 public DbSet<Product> Products { get; set; } = null!;

 public ProductRepository() => Database.EnsureCreated();

 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

 {

     optionsBuilder.UseMySql("server=127.0.0.1;port=3306;user=******;password=******;database=Shop",

         ServerVersion.AutoDetect("server=127.0.0.1;port=3306;user=******;password=******;database=Shop"));

 }

 public List<Product> GetProducts()

 {

     return Products.ToList();

 }

public partial class ShopContext : DbContext

public ShopContext()

{

}

public ShopContext(DbContextOptions<ShopContext> options)

    : base(options)

{

}

public virtual DbSet<Product> Products { get; set; }

public virtual DbSet<Purchase> Purchases { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

    => optionsBuilder.UseMySql("server=127.0.0.1;port=3306;user=******;password=******;database=Shop", ServerVersion.Parse("9.0.0-mysql"));

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

    modelBuilder

        .UseCollation("utf8mb4_0900_ai_ci")

        .HasCharSet("utf8mb4");

    modelBuilder.Entity<Product>(entity =>

    {

        entity.HasKey(e => e.IdProduct).HasName("PRIMARY");

        entity.ToTable("product");

        entity.Property(e => e.IdProduct).HasColumnName("idProduct");

        entity.Property(e => e.NameOfProduct)

            .HasMaxLength(45)

            .HasColumnName("nameOfProduct");

    });

    modelBuilder.Entity<Purchase>(entity =>

    {

        entity.HasKey(e => e.IdPurchase).HasName("PRIMARY");

        entity.ToTable("purchase");

        entity.HasIndex(e => e.IdProduct, "idProduct_idx");

        entity.Property(e => e.IdPurchase).HasColumnName("idPurchase");

        entity.Property(e => e.DateOfPurchase).HasColumnName("dateOfPurchase");

        entity.Property(e => e.IdProduct).HasColumnName("idProduct");

        entity.Property(e => e.QuantityOfPurchases).HasColumnName("quantityOfPurchases");

        entity.Property(e => e.TotalCost)

            .HasPrecision(10, 2)

            .HasColumnName("totalCost");

        entity.HasOne(d => d.IdProductNavigation).WithMany(p => p.Purchases)

            .HasForeignKey(d => d.IdProduct)

            .HasConstraintName("idProduct");

    });

    OnModelCreatingPartial(modelBuilder);

}

partial void OnModelCreatingPartial(ModelBuilder modelBuilder);

public partial class MainWindow : Window

public MainWindow()

{

    InitializeComponent();

    ProductRepository productRepository = new() ;

    List <Product> products=productRepository.GetProducts();

}

private void Button_AddProducts(object sender, RoutedEventArgs e)

{

    DirectoryOfProducts directoryOfProducts = new DirectoryOfProducts();

    directoryOfProducts.Show();

}

Hello. I'm writing an application in wpf, for the first time I connected Entity Framework and MySQL. I created the database myself, after which Entity Framework built the classes itself. I wanted to display product values from a table. But an error appears - there is no primary key. Where did I make a mistake? Why does this happen and how to correctly register CRUD operations. This is my first time practicing Entity Framework

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
751 questions
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,784 questions
0 comments No comments
{count} votes

Accepted answer
  1. Hongrui Yu-MSFT 2,465 Reputation points Microsoft Vendor
    2024-07-10T09:12:04.87+00:00

    Hi,@vitaminchik. Welcome to Microsoft Q&A. 

    Reason: Primary key constraint name is duplicated.

    In ShopContext, when defining the primary key of the Product and Purchase tables.

    
    entity.HasKey(e => e.IdProduct).HasName("PRIMARY");
    
    entity.HasKey(e => e.IdPurchase).HasName("PRIMARY");
    
    

    The primary key constraint name defined by HasName is repeated.

     

    Solution: Modify the primary key constraint names of the database and EF to make them different.

     

    Attach: The ProductRepositor you defined doesn't seem to make sense and will throw an error at runtime.

     

    You could use ShopContext to manipulate data directly. You could refer to the following methods:

    
    ShopContext shopContext = new ShopContext();
    
    var list1 = shopContext.Purchases.ToList();
    
    var list2 = shopContext.Products.ToList();
    
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.