Use SCOPE_IDENTITY to fetch the ID of an insert

1

I have a user table where when adding a user I can assign several hotels, which is another insert to a table from many to many. Researching a bit I can use the scope_identity() to be able to do this since it brings me the last record of the current session but reading about it I do not know how to use it or apply it in my code.

How can I apply it with Linq or with Entity Frammework? Is there an alternative?

Here my ActionResult where I do the insert. I only add a user but I can not find how to add the multiple hotels since I need the user's id inserted.

 public ActionResult CrEd([Bind(Include = "IdUsuario,Nombre,Contrasena,Descripcion,Estatus,IdRol")] Usuarios usuarios, int? bandera)
        {
            if(bandera == 1)
            {
                if (ModelState.IsValid)
                {
                    db.Usuarios.Add(usuarios);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }

                ViewBag.IdRol = new SelectList(db.UsuariosRol, "IdRol", 

"Nombre", usuarios.IdRol);
                    return View(usuarios);
            }
      }
    
asked by Roberto Dominguez 24.07.2017 в 23:06
source

1 answer

4

When you make a context.Entity.Add(entity) and then a context.SaveChanges() , entity framework executes a SELECT SCOPE_IDENTITY() and assigns the value to the property that is marked with the attribute [Key] .

Suppose that your Users entity has an Id property marked with the Key attribute:

public class Usuarios
{
  [Key]
  public int Id { get; set;}

  //...
}

Then when saving:

   db.Usuarios.Add(usuarios);
   db.SaveChanges();
   int scope_identity_id = usuarios.Id; // id tendra el id asignado por la base de datos
    
answered by 24.07.2017 / 23:53
source