I have the method below which will insert new records into a specific DbSet in my In Memory Ef Core database
public static async Task SaveDataToEntitySetAsync<TEntity>(DbContext context,List<TEntity> list)
where TEntity : BaseEntity
{
if(list.Any() == false)
return;
var dbSet = context.Set<TEntity>();
var existingData = await dbSet.Select(x=>x.Id).ToListAsync();
list.RemoveAll(x => existingData.Contains(x.Id));
await dbSet.AddRangeAsync(list);
}
I have a Currency db Set. Another Db Set that is processed before this has a foreign key to Currency. Because of this I am assuming a record is being added to the currency table.
Is there any way that in this specific scenario I can prevent foreign key records being added in this way?
When I get to processing the currency entity set I was expecting to see data in the DbSet but there is nothing in there?
I actually will need to go the other way around if I can get this to work anyway, i.e. delete the record that is in the context and replace with the currency in the main list
Im using Ef Core for .NET 3.1
I have also tried the logic below which should just attach the parent without attempting to do anything with the children but the issue still occurs
public static async Task SaveDataToEntitySetAsync<TEntity>(DbContext context,List<TEntity> list) where TEntity : BaseEntity
{
if(list.Any() == false)
return;
var dbSet = context.Set<TEntity>();
foreach (var item in list)
{
try
{
dbSet.Attach(item);
context.Entry(item).State = EntityState.Added;
await context.SaveChangesAsync();
}
catch (Exception e)
{
throw new Exception($"Error processing {item.GetType().Name} with Id {item.Id}: {e.Message}");
}
}
}
Paul
question from:
https://stackoverflow.com/questions/65876553/key-already-exists-error-but-no-data-shown-in-dbsets-in-memory-ef-core 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…