使用EntityFramework插入多个对象?

时间:2011-08-31 23:54:05

标签: entity-framework linq-to-entities entity-framework-4.1

我将我需要的东西构建到IEnumerable中,然后我需要将集合插入到数据库中,但无法弄清楚如何。请看一下我的代码段:

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;
    }

}

如果我必须将'assocs'转换为list然后逐个插入,那真的很难过。

1 个答案:

答案 0 :(得分:1)

您无需将assocs IEnumerable<T>转换为List<T>,但是,您需要逐个插入:

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