1

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; } } } 
4
  • I guess you are setting the Id property of BankAccount when it is generated by the database, or visa versa. Need to know the definition of the BankAccount table, the BankAccount type and what fields are posted from the client to be able to tell.
    – Richard
    CommentedApr 23 at 8:51
  • Please show us the BankAccount entity class!
    – marc_s
    CommentedApr 23 at 9:21
  • 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; } } }CommentedApr 23 at 11:44
  • update the question. don't post code in comments.
    – Fran
    CommentedApr 23 at 14:57

1 Answer 1

1

EF's default behaviour for PKs that match a naming convention of "Id" or "{Entity}Id" (I.e. "BankAccountId" for a BankAccount entity) is to treat them as Identity columns, expecting the database to populate them for new records. In these cases the default Int (0) would be replaced with a new ID from the database after SaveChanges is called.

Your code has disabled this behaviour with:

[DatabaseGenerated(DatabaseGeneratedOption.None)] public int BankAccountID { get; set; } 

DatabaseGeneratedOption.None tells EF that you will populate the BankAccountID manually for new records before saving. You are either not doing that, or any entered BankAccountID is not being passed along. Normally with Int PKs you will want to use identity columns so your issue will likely be resolved by removing that DatabaseGenerated attribute or switching it to DatabaseGeneratedOption.Identity. the None option is more for cases where you have a meaningful string PK that is computed or a data type like Guid and the database engine cannot handle the key generation. This can also apply to scenarios where data is imported to a database from another source of truth that is responsible for key generation.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.