【问题标题】:Database operation expected to affect 1 row(s) but actually affected 0 row(s). Entity's collection not tracked?数据库操作预计会影响 1 行,但实际上会影响 0 行)。未跟踪实体集合?
【发布时间】:2021-04-18 03:06:04
【问题描述】:

我收到此错误:

数据库操作预计会影响 1 行,但实际上会影响 0 行

向实体集合添加新元素时。

Domain 项目中的基类:

public class Tour
{
        private List<Stop> _stops;
        
        public Guid Id { get; private set; }

        public Tour(Guid id)
        {
            Id = id;
            _stops = new List<Stop>();
        }

        public IReadOnlyList<Stop> Stops { get { return _stops; } }
        
        public void AddStop(Stop newStop)
        {
            //some logic and checking
            _stops.Add(newStop);
        }
}

public class Stop
{
        public Stop(Guid id)
        {
            Id = id;
        }

        public Guid Id { get; private set; }
}

我在Infrastructure 项目中的DbContext

public class TourDbContext : DbContext, ITourDbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=db");
    }
    
    public DbSet<Tour> Tours { get; set; }
    public DbSet<Stop> Stops { get; set; }
}

Application 项目中调用AddStopToTour() 时抛出异常。

DbContext 的接口,基于:https://github.com/jasontaylordev/CleanArchitecture

public interface ITourDbContext
{
    public DbSet<Tour> Tours { get; set; }
    public DbSet<Stop> Stops { get; set; }
    Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}

public class SomeClass
{
    ITourDbContext _context;

    public SomeClass(ITourDbContext context) 
    {
        _context = context;
    }

    public async Task AddStopToTour(Guid id)
    {
        var tour = await _context.Tours
                                 .Include(x => x.Stops)
                                 .SingleOrDefaultAsync(e => e.Id == id);

        tour.AddStop(new Stop(Guid.NewGuid());
        await _context.SaveChangesAsync(); //Exception
    }
}

EF Core 是否应该能够自动跟踪这些更改并向 Stops 表添加 1 个新行?我是否缺少实体上的其他配置?

【问题讨论】:

  • 你的 DbContext 在哪里?尝试将 I ReadOnlyList 更改为 IList 并查看它是否有效。
  • 它不适用于 IList,也不适用于 List。 dbcontext 在哪里是什么意思?
  • 您已提供所有必要的代码来重现该问题。转到stackoverflow中的如何提问部分。现在,如果有人想解决您的问题,他们怎么知道您在 TourDbContext 中写了什么。
  • 更新问题,草率见谅。
  • 您的简单模型不符合正确跟踪的 EF 要求。 Tour 对象上的 Stops 永远不会按照设计在 Tour 对象上进行跟踪。

标签: c# entity-framework-core


【解决方案1】:

问题在于,通过手动生成我的 ID,新实体获得了 Modified 状态,而不是 Added 状态。修复方法是使用 Fluent API 的 .ValueGeneratedNever() 方法和 modelBuilder

见:https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.x/breaking-changes#detectchanges-honors-store-generated-key-values

【讨论】:

    猜你喜欢
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多