I need to make an insert in the Entity Framework and at the same time it returns the code of the inserted object, thus preventing further access to the bank.
I need to make an insert in the Entity Framework and at the same time it returns the code of the inserted object, thus preventing further access to the bank.
I understand that you want the return of the Id of an object, if the Id column is integer and IDENTITY
.
Considering that the mapping was done within the framework of the Entity Framework:
[DisplayColumn("Nome")]
public class Fruta
{
[Key]
public int FrutaId { get; set; }
[Required]
public String Nome { get; set; }
...
}
Just insert and read the object id:
var fruta = new Fruta { Nome = "Laranja" };
context.Frutas.Add(fruta);
context.SaveChanges();
var idDaFruta = fruta.FrutaId;