简体   繁体   中英

Execute Find/Update Xunit test cases without using AsNoTracking()

I am using following Nuget packages in my Unit test project created in .Net core 2.0 application.

在此处输入图片说明

I have created a InMemory database for Unit Testing.

Whenever I execute a unit test case that includes Update operations , I get an exception

"the instance of entity type 'tablename' cannot be tracked because another instance with the same key value for {Id} ia already being tracked.When attaching existing entities,enure that only once entity instance with a given key value is attached".

This is due to FindByAsync method which contains AsNoTracking() method. Method looks something like as shown below.

public virtual FindByAsync()
{
     Query= Query.AsNoTracking().AsExpandable.().Where(predicate);
}

When I comment this AsNoTracking() function. The Unit test case succeeds.

Any ideas, suggestions or workarounds that will help me execute failing test cases successfully.

Tracking behavior controls whether or not Entity Framework Core will keep information about an entity instance in its change tracker. If an entity is tracked, any changes detected in the entity will be persisted to the database during SaveChanges().

Tracking queries

using (var context = new BloggingContext())
{
    var blog = context.Blogs.SingleOrDefault(b => b.BlogId == 1);
    blog.Rating = 5;
    context.SaveChanges();
}

No-tracking queries

using (var context = new BloggingContext())
{
    var blogs = context.Blogs
        .AsNoTracking()
        .ToList();
}

If the entity instances are modified, this will not be detected by the change tracker and SaveChanges() will not persist those changes to the database.

More info

If you follow this in your code and you will not encounter issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM