VRM VRM - 3 months ago 13
ASP.NET (C#) Question

How to get the AutoGenerated ID when using SaveChanges in ASP.Net MVC. My current method seems inefficient

I have a StudentTable

(
(ID INT PRIMARY KEY IDENTITY(1,1),
NAME NVARCHAR(50) NOT NULL,
.....
)


The model definition is

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }

[Column("NAME")]
[Required(AllowEmptyStrings=false, ErrorMessage="Name is required")]
public string Name { get; set; }
........


I need to get the Auto Generated ID in the database whenever I insert A record in the Student Table using

isDAL.StudentTable.Add(scTemp.StudentInfo);
isDAL.SaveChanges();


Here isDAL is the Data Access Layer which inherits DBContext class from Entity Framework.

Right now I am using a trigger which gets the ID and stores it in the LASTINSERTED table which is defined as

CREATE TABLE LASTINSERTED
(
INT INSERTEDID
)


I use the following code to get it

intGeneratedID = isDAL.LASTINSERTED.ToList<Inserted>()[0].InsertedID;


Inserted is a dummy model which is defined as:

public class Inserted
{
[Required]
[Column("InsertedId")]
public int InsertedID { get; set; }
}


After getting the ID, the data in the table is deleted. Is there a better way? Create an extra record and the querying the table again seems inefficient.

Answer

You don't need to use trigger here. Just do as shown below.

isDAL.StudentTable.Add(scTemp.StudentInfo);
isDAL.SaveChanges();
var yourPkId=scTemp.StudentInfo.ID;//this is your Auto generated PK Id

How easy it is... :D

Comments