实体框架核心未跟踪ICollection

时间:2016-12-19 15:05:31

标签: c# entity-framework .net-core

我有两个班级:

public class TestProduct
{
    public ICollection<Tester> Collection { get; set; }
}

public class Tester
{
    public TestProduct TestProduct { get; set; }
}

我想跟踪对Collection的更改,当你向它添加内容时,我想跟踪它。但是,在下面的代码中,如果我向其集合中添加了某些内容,则集合所在的TestProduct对象永远不会标记为已修改,只有添加到集合中的对象才会标记为已修改。如何将TestProduct标记为已修改?

public class BaseDbContext : DbContext
{
    public BaseDbContext(DbContextOptions<BaseDbContext> options) : base(options)
    {

    }

    public DbSet<TestProduct> TestProducts { get; set; }
    public DbSet<Tester> Testers { get; set; }

    public int SaveChangesForAudit()
    {
        foreach (var moddedEntity in ChangeTracker.Entries()
            .Where(p => p.State == EntityState.Modified))
        {
            var state = moddedEntity.State;
            // logic for doing something with state change, here I would expect TestProduct to show up, not Tester
        }
    }
}

测试我正在运行,以供参考:

    [Fact]
    public void EditProduct_HandlesListChanges()
    {
        var testerId = Guid.NewGuid();
        using (var context = CreateContext("EditProduct_HandlesComplexProduct"))
        {
            context.TestProducts.Add(new TestProduct()
            {
                Created = DateTime.Now,
                Deleted = false,
                Id = Guid.NewGuid(),
                Name = "testproduct",
                TenantId = Guid.NewGuid(),
                Collection = new List<Tester>()
            });
            var tester = new Tester() {Id = testerId};
            context.Testers.Add(tester);
        }
        using (var context = CreateContext("EditProduct_HandlesComplexProduct"))
        {
            var prod = context.TestProducts.Include(tp => tp.Collection).Include(tp => tp.SubType).FirstOrDefault();
            var tester = context.Testers.First(x => x.Id == testerId);
            Assert.NotNull(prod);

            tester.TestProduct = prod;
            prod.Collection = new List<Tester>() { tester};

            context.SaveChangesForAudit(); //Here I will Audit changes
            Assert.Equal(1, prod.Versions.Count);

            context.Database.EnsureDeleted();
        }
    }

    private static InfrastructureTestDbContext CreateContext(string dbName)
    {
        var builder = new DbContextOptionsBuilder<BaseDbContext>();
        builder.UseInMemoryDatabase(dbName);
        return new InfrastructureTestDbContext(builder.Options);
    }

1 个答案:

答案 0 :(得分:0)

我认为这是问题所在

prod.Collection = new List<Tester>() { tester};

我认为变更跟踪器正在使用原始集合,并且无法跟踪创建的新列表,因此如果您这样做,则可能会起作用:

prod.Collection.Clear();
prod.Collection.Add(tester);