LP13
LP13

Reputation: 34089

How to get newly added entities in EF Core

I am adding new entity by creating the instance using inline syntax.

    public async Sys.Task<IEnumerable<Car>> CreateCars()
    {
        for (int i = 0; i < 2; i++)
        {
            await _dbContext.Cars.AddAsync(new Car()
            { 
               // set properties here                 
            });
        }

        await _dbContext.SaveChangesAsync();

        // How do return list of newly added Cars here without querying database
    }

How do i return newly added Car without querying the database?

One option i know is add new instance to list, and use AddRange method of dbContext like below

    public async Sys.Task<IEnumerable<Car>> CreateCars()
    {
        var list = new List<Car>();
        for (int i = 0; i < 2; i++)
        {
            list.Add(new Car()
            {

            });
        }

        await _dbContext.Cars.AddRangeAsync(list);
        await _dbContext.SaveChangesAsync();

        return list;          
    }

But i would like to avoid creating unnecessary instance of list. I am using EF Core 2.2.4

Upvotes: 2

Views: 1528

Answers (2)

Dejan
Dejan

Reputation: 10323

Use the Local property of your Cars DbSet. I contains a local view of the tracked entities.

Upvotes: 2

Jan Paolo Go
Jan Paolo Go

Reputation: 6522

There doesn't seem to be a built-in function for that. You could make a generic extension method though.

public static class DbSetExtensions
{
    public static async Task<T[]> AddRangeAsyncExt<T>(this DbSet<T> dbSet, params T[] entities) where T : class
    {
        await dbSet.AddRangeAsync(entities);
        return entities;
    }

    public static async Task<IEnumerable<T>> AddRangeAsyncExt<T>(this DbSet<T> dbSet, IEnumerable<T> entities) where T : class
    {
        await dbSet.AddRangeAsync(entities);
        return entities;
    }
}

// use case 1
var cars = await _dbContext.Cars.AddRangeAsyncExt(new Car(), new Car(), new Car());

// use case 2
var cars = await _dbContext.Cars.AddRangeAsyncExt(
    new[] { 1, 2, 3 }
    .Select(i => new Car
    {
        // set properties here
    }));

Upvotes: 0

Related Questions