m0s
m0s

Reputation: 4280

Inserting multiple objects using EntityFramework?

I build up stuff that I need into an IEnumerable and then I need to insert the collection into the database, but can't figure how. Please take a look at my code snippet:

public void CopyPonyJetpacks(Pony p_s, Pony p_d)
{
    try
    {
        using (var scope = new TransactionScope())
        {

            var assocs = from x in p_s.Pony_Jetpacks
                         select new Pony_Jetpacks()
                         {
                             Id=Guid.NewGuid(),
                             JetpackId=x.JetpackId,
                             PonyId=p_d.Id
                         };

            data.Pony_Jetpacks.AddObject(assocs); //This doesn't work, what to do?

            data.SaveChanges();
            scope.Complete();
        }
    }
    catch (Exception e)
    {
        throw e;
    }

}

It would be really sad if I had to convert the 'assocs' into list and then insert one by one.

Upvotes: 0

Views: 988

Answers (1)

Slauma
Slauma

Reputation: 177153

You don't need to convert your assocs IEnumerable<T> into a List<T> but yes, you need to insert it one by one:

foreach (var assoc in assocs)
    data.Pony_Jetpacks.AddObject(assoc);

Upvotes: 1

Related Questions