Entity Framework, Code First is used. There are 2 models - User and Topic. 1 user can have multiple topics.

public class User { public int Id { get; set; } public string Name { get; set; } public virtual ICollection<Topic> Topics { get; set; } } public class Topic { public int Id { get; set; } public string Title { get; set; } public int UserId { get; set; } public User User { get; set; } } 

It is necessary to make such an addition (topic objects inside the user object):

 using (MyDbContext context = new MyDbContext()) { // Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ с нСсколькими Ρ‚ΠΎΠΏΠΈΠΊΠ°ΠΌΠΈ User user = new User { Name = "ExampleName", Topics = new List<Topic> { new Topic { Title = "First topic" }, new Topic { Title = "Second topic" }, } }; // Заносим Π² Π±Π°Π·Ρƒ всС сразу context.Users.AddOrUpdate(user); // ΠŸΡ€ΠΎΠΉΠ΄Π΅Ρ‚ Π»ΠΈ Π΄ΠΎΠ±Π°Π²Π»Π΅Π½ΠΈΠ΅? Добавятся Π»ΠΈ Ρ‚ΠΎΠΏΠΈΠΊΠΈ? context.SaveChanges(); } 

It is necessary that the user himself and his 2 topics be added, without first resorting to adding the user, and then the topics separately. Is it possible to do something similar using only context.Users.AddOrUpdate(user); Which also already contains topics?

    1 answer 1

    This is possible to do. In order for it to work, you need to explicitly indicate the link in the added Topic , to which User they belong. The easiest way is to specify the UserId property of each Topic . Even if there is still no such User in the database, it will first be added, and then all its associated child objects will be added. Then your code will be

     using (MyDbContext context = new MyDbContext()) { int userId = 1; // Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ с нСсколькими Ρ‚ΠΎΠΏΠΈΠΊΠ°ΠΌΠΈ User user = new User { Id = userId, Name = "ExampleName", Topics = new List<Topic> { new Topic { UserId = userId, Title = "First topic" }, new Topic { UserId = userId, Title = "Second topic" }, } }; // Заносим Π² Π±Π°Π·Ρƒ всС сразу context.Users.AddOrUpdate(user); // ΠŸΡ€ΠΎΠΉΠ΄Π΅Ρ‚ Π»ΠΈ Π΄ΠΎΠ±Π°Π²Π»Π΅Π½ΠΈΠ΅? Добавятся Π»ΠΈ Ρ‚ΠΎΠΏΠΈΠΊΠΈ? context.SaveChanges(); }