EF Core 7 - System.InvalidOperationException

Raymart Atienza 36 Reputation points
2023-01-25T17:11:00.65+00:00

Hi,

Can someone please help? I am trying to insert a record with an FK using DBContext. EF Core keeps saying that the Country is already tracked. I am aware that EF Core thinks that I am inserting a new country but that's not my intention. In the below code, "P" is an entity that represents a province. I am already using the AsNoTracking() and the EntityState.Detached, so I'm wondering what else I missed. Country is the parent table and Province is the child table.

public static async Task<Country> GetCountryByISOCodeAsyncNoTracking(string _CountryISOCode)
{
   using MyDBContext Context = new();
   Country C = await Context.Country.AsNoTracking().SingleOrDefaultAsync(a => a.ISOCode == _CountryISOCode);
   await Context.DisposeAsync();
   if (C != null)
   {
      return C;
   }
Province P = new();
P.PSGCCode = fields[0];
P.ProvinceName = fields[1];
Country C = await AddressBook.GetCountryByISOCodeAsyncNoTracking(fields[2]);
if (C != null)
{
    Context2.Entry<Country>(C).State = EntityState.Detached;
    P.Country = C;
    Context2.Add<Province>(P);
}
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
697 questions
{count} votes