Get Auto Identity Key after Insert via EF

回眸只為那壹抹淺笑 提交于 2019-11-26 19:33:57

问题


Is there a straight forward way of retrieving a DB auto generated primary key when adding a record via Entity Framework 4.1?

For example:

dbcontext.Entity_Tables.Add(new Entity_Table { item1 = val1, item2 = val2 });
dbcontext.SaveChanges();
newPK = ???;

The SQL equivalent would be:

newPK = executeOnDB("INSERT INTO Entity_Table (item1, item2) VALUES (val1, val2);SELECT @@Indentity";);

BTW I'm using MySQL but the SQL would be the same as on MSSQL


回答1:


I believe EF should update your entity object with the identity:

var entity = new Entity_Table { item1 = val1, item2 = val2 };
dbcontext.Entity_Tables.Add(entity);
dbcontext.SaveChanges();
int newPK = entity.ID;


来源:https://stackoverflow.com/questions/8435462/get-auto-identity-key-after-insert-via-ef

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!