EF Core Duplicate entry Exception

EF core throws an exception in the project I am working on

MySqlException: Duplicate entry ‘2’ for key ‘customers.IX_Customers_UserID’

UserID gives such an error when it is present I do not understand exactly what the error is, please help

public class Context : DbContext
{
    public DbSet<Product> Products { get; set; }

    public DbSet<Category> Categories { get; set; }

    public DbSet<User> Users { get; set; }

    public DbSet<Customer> Customers { get; set; }

    public DbSet<Address> Addresses { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        //optionsBuilder.UseSqlite("Data Source = Shop.db");
        //optionsBuilder.UseSqlServer(@"Data Source = (localdb)v11.0; Initial Catalog=ShopDb; Integrated Security = SSPI;");
        optionsBuilder.UseMySql(@"server=localhost;port=3306;database=ShopDb1;user=root;password=admin123;");
    }

    public Context()
    {
        Database.EnsureCreated();

    }
}

public class User
{
    public int ID { get; set; }

    public string UserName { get; set; }

    public string Email { get; set; }

    public Customer Customer { get; set; }

    

    public List<Address> Addresses { get; set; }
}

public class Customer
{
    public int ID { get; set; }

    public int IdentifyNumber { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public User User { get; set; }
    [Required]
    public int UserID { get; set; }
}

public class Suplier
{
    public int ID { get; set; }

    public string Name { get; set; }

    public string TaxNumber { get; set; }

}

public class Address
{
    public int ID { get; set; }

    public string FullName { get; set; }

    public string Title { get; set; }

    public string Body { get; set; }


    public User User { get; set; }

    public int UserID { get; set; }
}

public class Product
{


    public int ProductID { get; set; }
    [MaxLength(100)]
    [Required]
    public string Name { get; set; }

    public decimal Price { get; set; }

    public int CategoryID { get; set; }
}

public class Category
{

    public int CategoryID { get; set; }
    [MaxLength(100)]
    [Required]
    public string Name { get; set; }
}

class Program
{
    static void Main(string[] args)
    {

        using (var db = new Context())
        {
            var customer = new Customer()
            {

                IdentifyNumber = 123,
                FirstName = "Remzi",
                LastName = "Balakishiyev",
                UserID = 2


            };
            db.Customers.Add(customer);
            db.SaveChanges();
        }
        Console.ReadLine();
    }

    static void InsertUsers()
    {
        var users = new List<User> {
            new User() { UserName ="Remzi",Email = "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0a786f67706324686b666b61637963736f7c4a6d676b636624696567">[email protected]</a>"},
            new User() { UserName ="Xezri",Email = "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="166e736c647f3874777a777d7f657f6f736056717b777f7a3875797b">[email protected]</a>"},
            new User() { UserName ="Nurane",Email = "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e18f9493808f84cf958093978493858898849780a1868c80888dcf828e8c">[email protected]</a>"}
        };
        using (var db = new Context())
        {
            db.Users.AddRange(users);
            db.SaveChanges();
        }
    }

    static void InsertAddresses()
    {
        var addresses = new List<Address> {
           new Address(){FullName = "Remzi Balakisiyev", Title = "Ev addressi", Body = "Masalli",UserID=1},
           new Address(){FullName = "Remzi Balakisiyev", Title = "Ish addressi", Body = "Baki",UserID=1},
           new Address(){FullName = "Xezri Balakisiyev", Title = "Ev addressi", Body = "Masalli",UserID=2},
           new Address(){FullName = "Nurane Tarverdiyeva", Title = "Ev addressi", Body = "Naxcivvan",UserID=3},
           new Address(){FullName = "Rena Heyderova", Title = "Ev addressi", Body = "Xachmaz",UserID=2},
           new Address(){FullName = "Memmed Bedelov", Title = "Ev addressi", Body = "Sumqayit",UserID=1}
        };
        using (var db = new Context())
        {
            db.Addresses.AddRange(addresses);
            db.SaveChanges();
            Console.WriteLine("Ishledi");
        }
    }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

For each customer entity framework adds a new user with the primary key 2. To add a relationship to the user with id 2 you need to insert a user object to the user property.

var customer = new Customer()
        {

            IdentifyNumber = 123,
            FirstName = "Remzi",
            LastName = "Balakishiyev",
            User = db.Users.FirstOrDefault(x => x.ID == 2)


        };
db.Customers.Add(customer);
db.SaveChanges();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x