How to insert entity with ID in the Entity Framework

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();

However, the following exception is thrown:

  

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: Can not insert the value into column 'Id', table 'SIPP.dbo.Area'; column does not allow nulls.

    
asked by anonymous 05.01.2016 / 20:34

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);
    
05.01.2016 / 21:25