zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    light oj 1105 规律
    light oj 1071 dp(吃金币升级版)
    light oj 1084 线性dp
    light oj 1079 01背包
    light oj 1068 数位dp
    light oj 1219 树上贪心
    light oj 1057 状压dp TSP
    light oj 1037 状压dp
    矩阵快速幂3 k*n铺方格
    矩阵快速幂2 3*n铺方格
  • 原文地址:https://www.cnblogs.com/wu_u/p/10483865.html
Copyright © 2011-2022 走看看