Home > Mobile >  Adding same entity object more than once with EF Core
Adding same entity object more than once with EF Core

Time:01-14

In below code , I want to add myEntity object more than once to database using EF Core. but each time with different value on property id but all other properties are the same. How can I do this? because it's only adding 1 row in the database.

I want to do this because I don't want to repeat calling GetCurrentLocalDateTime() for each iteration and also in the else statement.

 var myEntity = _mapper.Map<AEntity >(entityDto);

     myEntity.updatedAt = _helper.GetCurrentLocalDateTime();
     myEntity.CreatedAt = _helper.GetCurrentLocalDateTime();
           

            if (entityDto.ids != null || entityDto.ids.Count > 0)
            {
                foreach (var id in entityDto.ids)
                {
                    myEntity.id = id;
                    await _dbContext.myEntities.AddAsync(myEntity);
                }
            }
           
            else
            {
                await _dbContext.myEntities.AddAsync(myEntity);
            }


            await _dbContext.SaveChangesAsync(); 

CodePudding user response:

You can't add a single instance of a class, change one of its properties, and add it again expecting a new instance to be added to your database. All that will happen is that you change the property of the single instance you have added.

Instead, you will need to map the DTO multiple times, so that you add multiple instance of your entity class to the DbSet.

You also need to use && instead of || in your if condition. Use OR (||) will result in a NullReferenceException if the entityDto.ids collection is null.

var now = _helper.GetCurrentLocalDateTime();
if (entityDto.ids != null && entityDto.ids.Count > 0)
{
    foreach (var id in entityDto.ids)
    {
        var myEntity = _mapper.Map<AEntity>(entityDto);
        myEntity.updatedAt = now;
        myEntity.CreatedAt = now;
        myEntity.id = id;
        await _dbContext.myEntities.AddAsync(myEntity);
    }
}
else
{
    var myEntity = _mapper.Map<AEntity>(entityDto);
    myEntity.updatedAt = now;
    myEntity.CreatedAt = now;
    await _dbContext.myEntities.AddAsync(myEntity);
}

await _dbContext.SaveChangesAsync(); 

CodePudding user response:

It uses it to add multiple data.Look at these

.AddRangeAsync() .AddRange()

you can try to keep your data in list and save it all at once with "addrange()"

  •  Tags:  
  • Related