我正在使用EF来添加记录.我想获得最后一个插入的ID.以下是我的代码:
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);
如何从var id迭代记录?
解决方法
如果您正在使用EF,那么重点是您不必使用原始sql.而是使用EF生成的对应于数据库表的对象类.
所以在你的情况下,我宁愿做这样的事情:
// 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; }