Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

c# - Key already exists error but no data shown in dbSets - in memory Ef Core

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...