Search code examples
.net-corerazorforeign-keys

Entity Framework Core - Cannot insert explicit value for identity column in table 'EntryType' when IDENTITY_INSERT is set to OFF


I am trying to create my first Razor Pages using .Net Core and have come across a problem. I have the following 2 models:

enter image description here

and:

enter image description here

As you can see, an Entry can have an Entry type... Pretty straight forward. The issue I have is when trying to create a new Entry record:

enter image description here

I am populating a SelectList as follows:

enter image description here

enter image description here

which is being consumed for display:

enter image description here

However when I attempt to create a new Entry I get the following error:

enter image description here

It seems as if it is not only trying to create an Entry record in the database, but also the EntryType that is against the new Entry, instead of just populating the foreign key value (EntityTypeId) in the database:

enter image description here

I am hoping someone might be able to point me in the right direction please.


Solution

  • Add a foreign key EntryTypeId to the Entry model

    public int EntryTypeId {get;set;} 
    

    Then bind the select in the view like this

    asp-for="Entry.EntryTypeId"
    

    This way, all the information for that EntryType are copied or mapped to the Entry entity you're creating using the EntryTypeId specified. You are trying to modify existing entry Id the way you currently do it.