本文介绍了通过EF插入后获取自动身份密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在通过Entity Framework 4.1添加记录时,是否有直接检索DB自动生成的主键的方法?例如:
dbcontext.Entity_Tables.Add(new Entity_Table {item1 = val1,item2 = val2});
dbcontext.SaveChanges();
newPK = ???
SQL等价物将是:
newPK = executeOnDB(INSERT INTO Entity_Table(item1,item2)VALUES(val1,val2); SELECT @@ Indentity;);
BTW我正在使用MySQL,但SQL将与MSSQL相同
解决方案
我相信EF应该使用身份更新您的实体对象:
var entity = new Entity_Table {item1 = val1,item2 = val2};
dbcontext.Entity_Tables.Add(entity);
dbcontext.SaveChanges();
int newPK = entity.ID;
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
解决方案
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;
这篇关于通过EF插入后获取自动身份密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!