How to insert entity with ID into Entity Framework

Asked

Viewed 194 times

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?

  • I’m not using.

  • 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.

  • I’m not using Code First either.

  • Are you sure that the Id object area is being filled in? The exception says that the Id is void, which leads me to believe that the condition for your if occur is not being reached, and for that to happen you probably have no data in the Area table.

  • 1

    Is there any record in the database? if not the correct code would be: area.Id = last != null ? last.Id + 1: 1;

  • 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.

Show 2 more comments

1 answer

2

Decorate the Id of Area with the following:

[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }

Instead of using:

_contexto.Entry(area).State = EntityState.Added;

Prefer:

_contexto.Area.Add(area);

Instead:

var last = _contexto.Area.AsEnumerable().LastOrDefault();

Prefer:

var last = _contexto.Area.Max(a => (int?)a.Id);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.