背景:EF Core项目中使用InMemory作为数据库提供程序,编写单元测试。
报错:“The instance of entity type 'Movie' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.”
public class MovieServiceTests : TestBase { private List<Movie> movies = new List<Movie> { new Movie{ Id = 1, ShortName = "复联1" }, new Movie{ Id = 2, ShortName = "复联2" } }; [Fact] public async Task DelMovieAsync_Test() { //Arrange dbContext.Movies.AddRange(movies); dbContext.SaveChanges(); var entryState = dbContext.Entry(movies[0]).State; // 此时为Unchanged //Mark: movieService中的Remove方法和模拟数据(Arrange)时所用到的是同一个dbContext,此时movies对象的EntryState为Unchanged //由于实体对象还在被追踪,导致The instance of entity type 'Movie' cannot be tracked dbContext.Movies.Attach(movies[0]).State = Microsoft.EntityFrameworkCore.EntityState.Detached; var movieService = new MovieService(mapper, dbContext, baseService.Object); //Act var movieId = movies[0].Id; var result = await movieService.DelMovieAsync(movieId); //Assert Assert.True(result.Code == CustomCodeEnum.Success); } }
public async Task<Result> DelMovieAsync(int movieId) { var result = new Result(); _dbContext.Movies.Remove(new Movie { Id = movieId }); var rows = await _dbContext.SaveChangesAsync(); result.Content = rows > 0; return result; }