Asp.net mvc 在不使用EF调用MVC中的SaveChanges之前从新记录获取密钥

Asp.net mvc 在不使用EF调用MVC中的SaveChanges之前从新记录获取密钥,asp.net-mvc,asp.net-mvc-5,crud,Asp.net Mvc,Asp.net Mvc 5,Crud,我使用的是没有实体框架的MVC5,希望在调用SaveChanges之前从新插入的记录中检索密钥。这是因为我需要密钥作为外键在不同的记录中工作 下面是更好地解释我想做什么的伪代码: 1) Create record for Person 2) var newPersonId = newly created personId from Person record 3) Create record for Employee, set its personId (foreign key) to be

我使用的是没有实体框架的MVC5,希望在调用SaveChanges之前从新插入的记录中检索密钥。这是因为我需要密钥作为外键在不同的记录中工作

下面是更好地解释我想做什么的伪代码:

1) Create record for Person

2) var newPersonId = newly created personId from Person record

3) Create record for Employee, set its personId (foreign key) to be equal to newPersonId

4) Person.SaveChanges
   Emplyee.SaveChanges
因此,问题在于步骤2


我了解到,在使用实体框架时,实现这一点的方法是在模型中与[ForeignKey(“xxx”)]建立关系,实体框架将接管一切。但是,由于我没有使用实体框架,我如何才能做到这一点呢?

如果您没有使用EF,那么为什么要保存更改呢

好的,您可以通过任何方式使用TransactionScope

using (TransactionScope transactionscope = new TransactionScope()){
     //some other code....

     Person.SaveChanges();
     Employee.PersonId = Person.Id;
     Employee.SaveChanges()

     //if any exception rised here, all the save changes will be reverted
     transactionscope.Complete();
    }

您需要包含
系统。事务
以及为什么在保存和创建员工记录之前无法保存人员并获取其ID?如果您使用GUID作为PK,您可以创建一个新的GUID,并使用此ID创建人员。此外,如果您未使用EF,步骤4和“保存更改”是怎么回事?第1步和第3步执行INSERT..@jleroohep:因为如果员工未能保存,我也希望能够回滚Person。