Use primary key during transaction in entity framework c# entity-framework entity-framework-core


I am creating few models, inserting them with "InsertAsync" and at the end i am saving the changes with entity framework core.

What i would like to do is:


var object2 = new table2()
                Action = 1,
                PrimaryRef = object1.primaryKey,


But the that value is null, do you know how could i have a second insert with the value?

I mean, if they are executed one by one, entity framework should be able to map the value, if so, anybody knows how? thanks.


Basically to make it more simple:

I have a foreach loop where add (without saving) several object in table1 and table2.

In the same loop then i have to log the primary keys of both the tables in table3 (two different rows)

And then save everything at the end.

how can i take let EF know to take those primaryKeys?

1/28/2019 3:11:10 PM

Popular Answer

You need to define a foreign key relation between the two database objects in Entity Framework.

So on your second entity (table2) you must add

[ForeignKey("PrimaryRefId")] public table1 PrimaryRef { get; set; }

And in your table1, make a reference back :

public Collection<table2> SecondaryObjects { get; set; }

Now EntiryFramework knows the tables are related and you can leverage that relation.

var t2 = new Table2 { Name = "Stuff child" };
var t1 = new Table1 { Name = "Stuff",  PrimaryRef = t2 };

1/28/2019 2:58:50 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow