I am performing a transaction in my controller. The first data I enter goes to the "Companies" table in my database, and when I do the .Add()
, the database assigns an Id automatically thanks to the Identity Specification.
To make the second record, I need to use that created Id to insert it into my other table. My question is, how can I do it?
using (DbContextTransaction dbTran = Datos.Database.BeginTransaction())
{
try
{
Empresas empresa = new Empresas()
{
Nombre = empresasObj.Nombre,
DireccionWeb = empresasObj.DireccionWeb,
};
Datos.Empresas.Add(empresa);
Datos.SaveChanges();
EmpresasModulos empresasModulos{
EmpresaId = ¿?; //Acá necesito el Id
};
dbTran.Commit();
RemoveDatos();
return RedirectToAction("Index");
}
}
I enter the data in the "Companies" table, its Name and its Web address, and the database assigns it an Id in the form of an integer or int
, and then in the second table I need to retrieve that created Id.
I am Using Entity Framework and Linq.
Using Linq you get the last record inserted into the table with the LastOrDeFault method :
Once you get the last record you can access any property of it.
In order to use Linq you must put in the usings :
As the colleague says in the comments, Entity Framework returns the Id after saving the changes SaveChanges() , so to obtain it following the structure of your code it would be like this