Search code examples
c#.netentity-frameworkentity-framework-4

adding List of objects to Context in ef


Is it possible to add list of object to Context in entity framework without using foreach addObject ?

thanks for help


Solution

  • Generally you can't do that - you have to do it in a loop. In some cases, however, you can avoid adding every object - specifically, if you have an entity graph and you add the parent node. E.g. if you have a Company object that has a collection of Employees:

    context.AddToCompanies(company);
    
    /* The following loop is not necessary */
    /* The employees will be saved together with the company */
    /*
    foreach (var employee in company.Employees)
    {
        context.AddToEmployees(employee);
    }*/
    
    context.SaveChanges();