2
How to insert an entity with ID in Entity Framework 6.0? That is, insert with ID because the table does not generate it. For example:
var last = _contexto.Area.AsEnumerable().LastOrDefault();
area.Id = last !=null ? last.Id + 1 : 1;
_contexto.Entry(area).State = EntityState.Added;
_contexto.SaveChanges();
But the following exception is cast:
System.Data.Entity.Infrastructure.Dbupdateexception: An error occurred while updating the Entries. See the Inner Exception for Details. ---> System.Data.Entity.Core.Updateexception: An error occurred while updating the Entries. See the Inner Exception for Details. ---> System.Data.Sqlclient.Sqlexception: Cannot Insert the value NULL into column 'Id', table 'SIPP.dbo.Area'; column does not allow nulls.
Is using Fluent api?
– Vinícius
I’m not using.
– Luídne
Can you post the code that performs the mapping? The entity with Data Annotations or the databasecontext code if you used code first from database.
– Vinícius
I’m not using Code First either.
– Luídne
Are you sure that the
Id
objectarea
is being filled in? The exception says that theId
is void, which leads me to believe that the condition for yourif
occur is not being reached, and for that to happen you probably have no data in the Area table.– Zignd
Is there any record in the database? if not the correct code would be: area.Id = last != null ? last.Id + 1: 1;
– Felipe Assunção
There is the Id on the object, which is the weirdest thing it says is null. And there are other records in the table that have been entered manually.
– Luídne