0

hi i am new in Microsoft entity framework core i create a simple windows form application with (net core 3.1 and Microsoft entity framework core) i have successfully create a Table which look like this

    using AplicationDbContext DbContext = new AplicationDbContext();
            Wholesaler tabPage = new Wholesaler()
            {
                NameOwner = NameOwner.Text,
                NameCompany = NameCompany.Text,
                Address = Address.Text,
                MobilePhoneNumber1 =  MobilePhoneNumber1.Text,
                MobilePhoneNumber2 =  MobliePhoneNumber2.Text,
                linePhone1 = LinePhone1.Text,
                linePhone2 = LinePhone2.Text,
                Email = Email.Text,
                Fax = Fax.Text
            };
DbContext.Wholesalers.Add(tabPage);
            DbContext.SaveChanges();

the problem is the NameCompany Is PK and i want to show massage box to the user "Name company already exists" and prevent from this error (SqlException: Violation of PRIMARY KEY constraint 'PK_Wholesalers'. Cannot insert duplicate key in object 'dbo.Wholesalers'. The duplicate key value is ().)

We_Go
  • 25
  • 4

1 Answers1

0
using AplicationDbContext DbContext = new AplicationDbContext();
        
            Wholesaler tabPage = new Wholesaler()           
        {
            NameOwner = NameOwner.Text,
            NameCompany = NameCompany.Text,
            Address = Address.Text,
            MobilePhoneNumber1 =  MobilePhoneNumber1.Text,
            MobilePhoneNumber2 =  MobliePhoneNumber2.Text,
            linePhone1 = LinePhone1.Text,
            linePhone2 = LinePhone2.Text,
            Email = Email.Text,
            Fax = Fax.Text
        };
        if (DbContext.Wholesalers.Any(s => s.NameCompany == NameCompany.Text))
        {
            MessageBox.Show($"Wholesaler: {NameCompany.Text} already exist ", "Name Company", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }
        DbContext.Wholesalers.Add(tabPage);
        DbContext.SaveChanges();
    }

found the answer here Check if Record Exists in Entity Framework

We_Go
  • 25
  • 4