Get ID immediately after insertion

3

Use Entity and LINQ. I would like to know how I get a generated ID soon after inserting a record, before anyone else can enter it too, ie ensure that that ID is the one I generated. Has as? Use Sql Server 2008, Entity, LINQ

    
asked by anonymous 26.05.2014 / 17:02

3 answers

4

The Entity Framework does it all for you. Here is an example:

var registroDaMinhaEntidade = new Entidade { Propriedade = "Uma propriedade qualquer, sei lá" };
context.Entidades.Add(registroDaMinhaEntidade);
context.SaveChanges();

// Depois do SaveChanges, se sua coluna for Identity, você deve ter o Id assim:
var idDaEntidade = registroDaMinhaEntidade.Id;
    
26.05.2014 / 17:11
3

Just do as the code below

Pessoa pessoa = new Pessoa();
pessoa.nome = "Paulo";
context.AddObject(pessoa);
context.SaveChanges();
int id = pessoa.Id;

After you call SaveChanges (); Entity already loads the Id for you.

    
26.05.2014 / 17:11
2

No Entity

context.SaveChanges();
int id = ClasseContexto.Id;

No SQL

SELECT @@IDENTITY

You could run the following statement in MS SQL (tSQL)

INSERT tabela_Exemplo (coluna1) values (@valor1)  IF (@@ERROR = 0) SELECT @@IDENTITY AS RETORNO

it would return a 'return' field with the ID value

Since it is a foreign key field

    
26.05.2014 / 18:47