• entity cannot be tracked


    背景: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;
    }
  • 相关阅读:
    PAT B1021 个位数统计 (15)
    PAT B1006 换个格式输出整数 (15)
    PAT A1058 A+B in Hogwarts (20)
    PAT A1027 Colors in Mars (20)
    PAT A1019 General Palindromic Number (20 分)
    PAT B1022 D进制的A+B
    J2EE
    MVC
    数据库长连接短连接
    twisted
  • 原文地址:https://www.cnblogs.com/wu_u/p/10483865.html
Copyright © 2020-2023  润新知