Grab ID immediately after insertion

Asked

Viewed 3,330 times

3

Entity and LINQ usage. I would like to know how I get a generated ID right after entering a record, before anyone else can enter it as well, that is, ensure that that ID is the one generated by me. Do you have how? Sql Server Usage 2008, Entity, LINQ

3 answers

5


The Entity Framework does this for you alone. Here’s 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;
  • Gypsy understood, but another person could have given an Internet too and I get the ID generated last and not what I generated. No sql server has a function that does this, IE, ensures that the generated ID is that and ready. I just don’t know which

  • So, but forget about it in the Entity Framework. It already takes the scope_identity automatically.

  • 1

    @pnet, the Entity framework already takes exactly the generated ID and puts it in the ID attribute of your Model, as Gypsy said.

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(); the Entity already loads p/ you the Id.

2

In the Entity

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

In 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

As long as it’s a foreign key field

Browser other questions tagged

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