EF Core in memory, delete unit testing giving error: entity already tracked

entity-framework-core in-memory-database

Question

I am working with entity framework core in memory to test my code.I created in memory context and added data. I have delete method which is going to delete record with id=1. Test method is throwing error following error:

The instance of entity type 'cats' cannot be tracked because another instance with the key value '{Id: 204}' is already being tracked When attaching existing entities, ensure that only one entity instance with a given key value is attached.

Could any one help me , how to resolve this issue. I tried different scenarios on internet, but nothing did not work.

Test.cs:

   [Fact(DisplayName ="Delete Service Must Return Result")]
    public void DeleteService()
    {
        var serviceId = _collectionFixture.context.cat.Where(x => x.Id == 201).AsNoTracking();

       var okObject = _collectionFixture.CatController.DeleteService(serviceId) as OkObjectResult;

          var baseResponse = okObject.Value as BaseResponse;
           Assert.True(baseResponse.Success);
    }

my service class:

public catResponse DeleteService(int serviceId) { try{

               var serviceDto = _Context.catserviceTreatment.Where(x => x.Id 
                           ==serviceId).AsNoTracking().firstordefault();

            if(serviceDto!=null)
            {


                    this._Context.catserviceTreatment.Remove(serviceDto);
                    this._Context.SaveChanges();

                   return new catResponse { Success = true, Error = "service 
                              deleted successfully" };
            }

           }catch(exception e)
           {
           } 
      }

my collection fixture:

      public catContext GetDbContext()
              {
                  var options = new DbContextOptionsBuilder<catContext>()
                 .UseInMemoryDatabase(Guid.NewGuid().ToString())

               .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)

                  .ConfigureWarnings(x => 
                 x.Ignore(InMemoryEventId.TransactionIgnoredWarning))
               //  .ConfigureWarnings(x=>x.Ignore(InMemoryEventId.))
                .EnableSensitiveDataLogging()
                   .Options;

                var context = new CatDirectoryContext(options);

            var catCategory = new List<catcategory>()
               {
                   new catCategory{Id=100,CategoryName="Youth 
                teereafjkd",UpdatedBy="Test",UpdatedWhen=DateTime.Now},
                 new catCategory{Id=101,CategoryName="Adult 
                fdsafd",UpdatedWhen=DateTime.Now},     
        };

        context.catcategory.AddRange(catCategory);
        context.SaveChanges();


        var catService = new List<catserviceTreatment>()
        {
            new catserviceTreatment{Id=200,Name="House of 
          Hope",Company="",
                Address ="2001 st street",City="alone 
           city",State="UT",ZipCode=8404,Category=null,
                CategoryId =100,Description="this is 
           description",UpdatedBy="test",UpdatedWhen=DateTime.Now},

            new catserviceTreatment{Id=201,Name="Odyssey 
             House",Company="",
                Address ="2001 st",City="bare 
               city",State="UT",ZipCode=84dfd,Category=null,
                CategoryId =101,Description="this is d 
                 description",UpdatedBy="test",UpdatedWhen=DateTime.Now},

        }
        context.catserviceTreatment.AddRange(catService);

        context.SaveChanges();

        return context;

   }
1
1
5/17/2019 2:49:41 PM

Popular Answer

I had the same error. During setup I added some test records starting with id 1. It appeared that the in memory database also starts numbering at 1 when new records are added, causing the "entity already tracked" error.

After I changed my initialization code to use ids as of 101, the problem was solved.

0
7/9/2019 2:35:04 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow