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;
    }
  • 相关阅读:
    spark 脚本示例
    R树的应用
    将博客搬至CSDN
    select
    注册页面的验证码的实现
    web项目.注册及登陆
    eclipse web 项目中遇到的问题总结
    Apache与Tomcat
    关于MVC整理
    JDBC
  • 原文地址:https://www.cnblogs.com/wu_u/p/10483865.html
Copyright © 2011-2022 走看看