0

I am using MVC5 without entity framework, and want to retrieve the key from a newly inserted record before calling SaveChanges. This is because I need the key to work as a foreign key in a different record.

Here's the pseudo code to better explain what I want to do:

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

Thus, the problem is step 2.

I read that the way to do this when using entity framework is to setup a relationsship in the model with [ForeignKey("xxx")], and entity framework will take of things. But as I don't use entity framework, how can I do this?

brinch
  • 2,544
  • 7
  • 33
  • 55

1 Answers1

1

If you are not using EF how come you have SaveChanges.

Ok, Any way you can use 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();
    }

and you need to have System.Transactions included

Rama Kathare
  • 920
  • 9
  • 29