how to save two tables linked by one to several simultaneously

Nakashi Learn 21 Reputation points
2022-11-09T14:26:29.6+00:00

for example Car and Simultaneous Image by first recovering the primary key of the car and assigning to the different images in a single Linq c# request

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
697 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,233 questions
{count} votes

Accepted answer
  1. Zhanglong Wu-MSFT 261 Reputation points Microsoft Vendor
    2022-11-11T06:35:01.833+00:00

    @Nakashi Learn ,

    Based on your description, it seems that you want to save a 1 to many relationship entities into database. like below:

     using (var context = new YourDbContext())  
        {  
            var car= new Car  
            {  
                Name = "My Dream Car",  
                Images= new List<Image>  
                {  
                    new Image{ CarColor = "Blue" },  
                    new Image{ CarColor = "Yellow" },  
                    new Image{ CarColor = "Red" }  
                }  
            };  
          
            context.Cars.Add(car);  
            context.SaveChanges();  
        }  
    

    Best regards,
    Zhanglong


0 additional answers

Sort by: Most helpful