Return Code object as inserted

8

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.

    
asked by anonymous 06.09.2014 / 20:45

1 answer

9

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;
    
07.09.2014 / 21:29