0

Something very simple that should work is not working for me, I have case like this

var equipment = new Equipment(); // This has Id column PK, INT and Identity
context.Equipment.Add(equipment);

var software = new EquipmentSoftware(); // This has primary key EquipmentId which is actually the Id of equipment table
software.EquipmentId = equipment.Id;

context.EquipmentSoftware.Add(software);

context.SaveChanges();

Now ideally this should work, it should create record of equipment software based on the id generated for equipment.

But it is not doing this and giving me primary key violation error for equipment software table because it is trying to enter EquipmentId - 0 in equipment software table, that means it is not taking the equipment id of the equipment that is generated

Any idea?

Edit

This all code is under transaction. So I want it all to get inserted in one go, that is why I do not want to use context.SaveChanges() to save equipment first and then use the Id, that way it will definitely work I know because then the record will be created for equipment in database and I don't want that partial inserts but all in one go.

Amir Molaei
  • 3,700
  • 1
  • 17
  • 20
Pawan Nogariya
  • 8,330
  • 12
  • 52
  • 105

2 Answers2

0

You need to call context.SaveChanges() first before you access equipment.Id. Please see this answer: How can I get Id of inserted entity in Entity framework?

Kei Huynh
  • 29
  • 5
  • I think there is no way to get Identity Id in advance in your case, however, my point is why would you want to use EquipmentId as the primary key? Wouldn't it better to be foreign key only? And then you can use a different way (also mentioned in the provided link) to sort it out. – Kei Huynh Mar 01 '19 at 16:59
  • I agree EquipmentId should be the foreign key, but this is how the design right now is and I cannot change it :) However in another way it makes sense since there is one to one mapping and a software is per equipment so there is no too harm to identify the record of software with EquipmentId. – Pawan Nogariya Mar 01 '19 at 17:00
  • And I am not trying to get the identity in advance. I mean this whole bunch of insertion request will go together and so ideally entity framework should know how to handle dependent objects. For foreign keys records this approach does work where entity framework finds the id in run time and assign it to the foreign key record – Pawan Nogariya Mar 01 '19 at 17:03
0

You can do it using the navigation property.
So, Instead of this statement:

software.EquipmentId = equipment.Id;  

you need to use this one:

software.Equipment = equipment; 
Amir Molaei
  • 3,700
  • 1
  • 17
  • 20