Saving a List<IEntity2>

Posts   
 
    
JSobell
User
Posts: 145
Joined: 07-Jan-2006
# Posted on: 25-Jun-2022 16:48:13   

How do I save a list of entities retrieved using Linq? I'm currently using this:

    public async Task SaveAsync(IEnumerable<IEntity2> entities, bool readback = false)
    {
        foreach (var entity in entities)
        {
            await AdapterToUse.SaveEntityAsync(entity, readback, false);
        }
    }

But for some reason it's not persisting my entities, and it is obviously inefficient. I can't see any way to convert a List<IEntity2> into an IEntityCollection2 which is what I assume I need to use with the Adapter's Save method?

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39760
Joined: 17-Aug-2003
# Posted on: 26-Jun-2022 10:16:37   

If you're fetching entities using a linq query, you can do:

var customers = ((ILLBLGenProQuery)q).Execute<EntityCollection<CustomerEntity>>();

This will return the result in an EntityCollection<T>, in this case EntityCollection<CustomerEntity>. There's also an Async variant.

If you don't want to do this, and have a List<T>, you can do:

var results = myLinqQuery.ToList();
var resultsAsEntityCollection = new EntityCollection<CustomerEntity>();
resultsAsEntityCollection.AddRange(results);
//...

Your code looks like it should save the entities properly though, but if they're not changed/marked as dirty then nothing will be done with them, perhaps that's it? If the entities are in a collection, they are also saved in a loop unless you enabled batching.

Frans Bouma | Lead developer LLBLGen Pro