1

I have two tables. One is the product (the basic table) and the other table is a product class (which has specific properties for the product class). I am keeping the ID of the product (from the product table) inside the specific table. The problem comes when I try to use unit of work. I have to get the ID of the added item in the product (basic) table but since I haven't commited the transaction, the ID doesn't exist (since I am using auto increment in my database). When I wasn't using unit of work I had the advantage of objects in C#, that they are reference types and I could easy get out the ID from the newly added product item (product table) right after I had saved it to the table with (context.SaveChanges() method) but now.... Any ideas? PS: MVC

susan
  • 11
  • 2
  • Try as per below: https://stackoverflow.com/questions/17523568/entity-framework-retrieve-id-before-savechanges-inside-a-transaction – Juhi Jun 05 '17 at 10:31
  • Try this , and upvote if u like https://stackoverflow.com/questions/36868254/how-do-i-get-db-generated-ids-back-when-using-repository-pattern/51673207#51673207 – X.Otano Aug 04 '18 at 10:20

1 Answers1

0

Do something like bellow code:

            db.MyJobContext.Add(job);
            db.SaveChanges();
            //get inserted Id
            int JobId = job.Id;

            var JobProvObj = new JobProvRel();
            JobProvObj.JobId = JobId;

            foreach (int P_id in Provinces)
            {
                JobProvObj.ProvinceId = P_id;
                db.MyJobProvRelContext.Add(JobProvObj);
                db.SaveChanges();
            }
MJ X
  • 8,506
  • 12
  • 74
  • 99