在MVC 4中获取最后插入记录的自增id

3
MVC 4对我来说一直是个难题。我正在使用SQL Compact数据库中的三个表。
首先保存Accounts表(已完成),但PhonesData表使用AccountsID作为外键。MVC 4通过ModelView完成所有的数据库工作,那么我该如何通过MVC 4从新添加的行中获取AccountsID并将其提供给Phones和Data模型,以便一切正确保存?

3
在调用 context.SaveChanges() 后,新添加的实体将拥有数据库创建的 id - SOfanatic
1个回答

9
您可以进行以下操作:
var account = new Account();
context.Accounts.Add(account);
context.SaveChanges();

var Phone = new Phone();
// account.Id will be populated with the Id from the Database.
// as long as it's the identity seed or set to NewID()(Sql Server)
phone.AccountId = account.Id;
...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接