Ali Ali -4 years ago 206
C# Question

DbUpdateException error occurred in EntityFramework.dll

So I get an DbUpdateException error every time i try to save my data.

This is my code:

tbl_UAM uam = new tbl_UAM
{
MDMRefNumber = tbxLastName.Text.Trim(),
SARId = tbxSARIdNewUAM.Text.Trim(),
FirstName = tbxFirstName.Text,
LastName = tbxLastName.Text,
CountryOfOrigin = cbxCountryOrigin.SelectedIndex,
PhoneNumber = tbxPhoneNumber.Text,
Center = Convert.ToInt16(cbxRRC.SelectedIndex),
Building = tbxBuilding.Text,
Floor = tbxFloor.Text,
SpecificDetails = tbxSpecificDetails.Text,
};

using (var context = new DemoDbEntities())
{
context.tbl_UAM.Add(uam);
context.SaveChanges();
}


and this is my error:


An unhandled exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll

Additional information: An error occurred while updating the entries. See the inner exception for details.


Now I know where the problem is. It's actually Identity specification problem because in my database I have turned auto-increment set to "Yes". I also know that I have to set Identity specification to false, I just don't know how to do it in my code and I cant really understand and implement it. Can someone explain to me how is it done?

Answer Source

You need to identify the ID column in your class definition. Something like this:

public  class tbl_UAM
{
    /// <summary>
    /// Gets or sets the entity identifier
    /// </summary>
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string FirstName {get; set;}

    // the rest of columns

}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download