mardi 16 juin 2020

How can you update a recently added instance of an entity in the same test?

Here's my problem. I would like to test a function in a controller that implements a simple update. I have the error code:

The instance of entity type 'Data' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked.

In my case, Data.Id is the primary key.

How can I put the data into the "database" before, without this error occurring? My assumption is that the data I enter before will be tracked and is in the "tracked state",and therefore no update is possible.

The idea is to test that that everything runs in UpdateData and also performs the update. The only thing that changes in the new data is for example a new "Data.Title" which is for example a string datatype.

I tryed to change EntityState for the "testData" but this does not help. I have already searched and tried a lot but I am at a loss.

The error occurs in the UpdateData() function while performing "db.Data.Update(data)".

Here's what I've programmed:

Controller:

public async Task<IActionResult> UpdateData(DataDto dataDto){
        var data = mapper.Map<Data>(dataDto);
        //some updating happens here
        db.Data.Update(data);
        wait db.SaveChangesAsync();
        return Ok();
}

HelperFunction:

public static ApplicationDbContext DbContext(){
        var options = new DbContextOptionsBuilder<ApplicaitonDbContext>
           .UseInMemoryDatabase(Guid.NewGuid().ToString())
           .Options;

        var context = new ApplicationDbContext(options);
        return context;
}

TestFunction:

[Fact]
public async void UpdateDataTest(){
        //here happens some Mapper initialization
        await using var context = HelperFunction.DbContext();
        await context.Data.AddAsync(testData);
        await context.SaveChangesAsync();
        var dataController = new DataController(context, mapper){};
        var result = await dataController.UpdateData(changedTestData);
        // do some UnitTest

}

Aucun commentaire:

Enregistrer un commentaire