【问题标题】:Retrieve auto increment id of last inserted record in MVC 4检索 MVC 4 中最后插入记录的自动增量 ID
【发布时间】:2013-07-18 01:49:54
【问题描述】:

MVC 4 对我来说是一个非常难以破解的难题。我在 SQL Compact 数据库中使用三个表。

Accounts 表首先保存(我已经这样做了),但PhonesData 表使用AccountsID 作为外键。 MVC 4 是否所有数据库都通过 ModelView 工作,那么我如何通过 MVC 4 从数据库中新添加的行中获取 AccountsID 并将其提供给电话和数据模型,以便正确保存所有内容?

【问题讨论】:

  • 调用context.SaveChanges()后,新添加的实体将拥有数据库创建的id

标签: c# asp.net-mvc entity-framework


【解决方案1】:

您可以执行以下操作:

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;
...

【讨论】:

    猜你喜欢
    • 2012-02-22
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 2016-11-06
    • 2012-12-19
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    相关资源
    最近更新 更多