Reputation: 1501
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."}
Upvotes: 3
Views: 15389
Reputation: 53958
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.
Upvotes: 1