I am using EF to add record. I want to get the last Inserted ID. Following is my Code:
string query = "INSERT INTO MyTable(PONumber, Status, UpdatedBy, UpdatedOn, CreatedOn) VALUES(@PO_NUMBER, '0', @STAFF, GETDATE(), GETDATE())";
parameterList = new List<object>();
parameterList.Add(new SqlParameter("@PO_NUMBER", poNumber));
parameterList.Add(new SqlParameter("@STAFF",staff));
parameters = parameterList.ToArray();
result = db.Database.ExecuteSqlCommand(query, parameters);
query = "SELECT NewID = SCOPE_IDENTITY();";
var id = db.Lists.SqlQuery(query);
How do I iterate record from var id
?
The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.
If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL.
IDENT_CURRENT() will give you the last identity value inserted into a specific table from any scope, by any user. @@IDENTITY gives you the last identity value generated by the most recent INSERT statement for the current connection, regardless of table or scope.
If you're using EF, the whole point is that you don't have to fiddle around with raw SQL. Instead, you use the object classes generated by EF corresponding to your database tables.
So in your case, I would much rather do something like this:
// create the EF context
using(YourEFContext ctx = new YourEFContext())
{
// create a new "MyTable" class
MyTable newEntity = new MyTable();
// set its properties
newEntity.PoNumber = poNumber;
newEntity.Status = 0;
newEntity.CreatedOn = DateTime.Now;
newEntity.UpdatedOn = DateTime.Now;
newEntity.UpdatedBy = staff;
// add new entity to EF context
ctx.MyTable.Add(newEntity);
// save changes to database
ctx.SaveChanges();
// read out your newly set IDENTITY value
int newIdentityValue = newEntity.ID;
}
Clean object-oriented code - no messy SQL needed at all!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With