Use primary key during transaction in entity framework

asp.net c# entity-framework entity-framework-core

Question

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:

MasterDbContext.table1.AddAsync(object1);

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

MasterDbContext.table2.AddAsync(object2);

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.

*** UPDATE

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
1
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 };

MasterDbContext.table1.AddAsync(t1);
1
1/28/2019 2:58:50 PM


Related Questions





Related

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