I want to create a test website for recording a company's information. After running the software and entering three data entries, everything goes well. However, after registering the fourth data entry, I get the following error:
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details. SqlException: Violation of PRIMARY KEY constraint 'PK_BankAccount'. Cannot insert duplicate key in object 'dbo.BankAccount'. The duplicate key value is (0).
The program throws an error at the following line:
await _context.SaveChangesAsync();
Meanwhile, when I manually enter the fourth and fifth values into the database from the SSOE section, there is no issue.
I am using Visual Studio 2022.
My code:
namespace ContosoUniversity.Pages.BankAccounts { public class CreateModel : PageModel { private readonly ContosoUniversity.Data.SchoolContext _context; public CreateModel(ContosoUniversity.Data.SchoolContext context) { _context = context; } public IActionResult OnGet() { return Page(); } [BindProperty] public BankAccount BankAccount { get; set; } = default!; // For more information, see https://aka.ms/RazorPagesCRUD. public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } _context.bankAccounts.Add(BankAccount); await _context.SaveChangesAsync(); return RedirectToPage("./Index"); } } }
I expected it to run without error.
sorry I have not latest BankAccount code but I send previous from backup:
using System.ComponentModel.DataAnnotations.Schema; namespace ContosoUniversity.Models { public class BankAccount { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int BankAccountID { get; set; } // public string Title { get; set; } public int Credits { get; set; } public ICollection<BankAccountMember> BankAccountMembers { get; set; } } }
BankAccount
when it is generated by the database, or visa versa. Need to know the definition of theBankAccount
table, theBankAccount
type and what fields are posted from the client to be able to tell.BankAccount
entity class!using System.ComponentModel.DataAnnotations.Schema; namespace ContosoUniversity.Models { public class BankAccount { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int BankAccountID { get; set; } // public string Title { get; set; } public int Credits { get; set; } public ICollection<BankAccountMember> BankAccountMembers { get; set; } } }