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
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
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;
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.
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