Suppose there are 2 tables. One table refers to another through a foreign key, which cannot be NULL. Entety2.Foreign refers to Entity1.Primary .

The key field is of type IDENTITY .

In order to perform an insert, I first create an entry in the main table and perform the save.

Then I create an entry in the second table and do Entety2.Foreign=Entity1.Primary .

Is it right to do this or is there a simpler way to work with dependent tables?

  • Judging by this , you can simply link the elements together, add to both lists and make one SaveChanges (). It’s also interesting if EF handles the reverse operation correctly - deleting both records together. - nzeemin
  • @nzeemin, if I'm not mistaken, then you need to remove the pens, if there is no cascading deletion ... - iluxa1810

1 answer 1

Suppose the models look something like this:

 public class Request { public int Id {get;set;} public virtual ICollection<RequestHistory> Histories {get;set;} } pubilc RequestHistory { public int ReqiestId {get;set;} } 

then you can use the navigation properties to insert a dependent entry:

 var request = // var history = // using(var db = new DefaultContext()) { db.Requests.Add(request); db.SaveChanges(); request.Histories.Add(history); db.Entry(request).State = EntityState.Modified; db.SaveChanges(); } 

based on documentation

should work like this:

 var request = // var history = // request.Histories.Add(history); using(var db = new DefaultContext()) { db.Requests.Add(request); db.SaveChanges(); } 

based on what the Entity Framework will add entries to the required tables

  • This is essentially the same thing that I am doing now, only without navigation properties. And there are no options, what would be for one of the EF preservation everything ruined itself? - iluxa1810
  • Ie, the records from both tables are not physically present in the database, and when the context is saved, the EF itself inserts the foreign key. - iluxa1810
  • @ iluxa1810 If you believe this, then the method I have given should work without the first db.SaveChanges() , if I understood correctly, this is what you want. - Bald