db.SaveChanges() results in System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll

asp.net asp.net-mvc c# entity-framework

Question

I am trying to add a Room into my database but keep getting the above error and cannot figure out why.

I am trying to insert:

ID: 12345 Name: Room

There is no entry in the database with an ID of 12345, in fact there are no entries, I cannot insert anything.

Model

public class Room
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID { get; set; }

    public string name { get; set; }

    public virtual ICollection<RoomItem> RoomItems { get; set; }
    public virtual ICollection<StaffRoom> StaffRooms { get; set; }
    public virtual ICollection<RoomAudit> RoomAudit { get; set; }
}

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID, name")] Room room)
{

    db.Rooms.Add(room);
    db.SaveChanges();
    return RedirectToAction("Index");

}

Connection String

<connectionStrings>
  <add name="UniversityContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=RoomAudit;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>

I have been trying to figure this out for hours so any help is massively appreciated.

EDIT

Full error:

An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code

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

Inner exception 1:

{"An error occurred while updating the entries. See the inner exception for details."}

Inner exception 2:

{"Cannot insert explicit value for identity column in table 'Room' when IDENTITY_INSERT is set to OFF."}

1
2
11/17/2016 7:04:04 PM

Popular Answer

The problem is the following:

Cannot insert explicit value for identity column in table 'Room' when IDENTITY_INSERT is set to OFF

The ID is an identity column and you try on insert to set this value. A quick workaround would have been to alter your column and remove the identity. However, I am not sure if that is the most appropriate design solution for your case. It is quite often that primary keys to be defined as auto incremented (identity columns) integer values. However, this is not a rule that you should always follow it. It depends as I previously said on your design choices.

1
11/17/2016 7:07:25 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow