Reputation: 1721
I have two classes:
public class TestProduct
{
public ICollection<Tester> Collection { get; set; }
}
public class Tester
{
public TestProduct TestProduct { get; set; }
}
I want to track changes to Collection, when you add something to it, I want to track it. However, in the code below, the TestProduct object where the collection is, is never marked as Modified if I add something to its collection, only the object that is added to the collection is marked as Modified. How do I get TestProduct marked as modified?
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
}
}
}
The test i'm running, for reference:
[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);
}
Upvotes: 1
Views: 1346
Reputation: 613
I think this is the problem
prod.Collection = new List<Tester>() { tester};
I assume that the change tracker is working with the original collection and has no way to track the new list that is created, so it probably would work if you do like this instead:
prod.Collection.Clear();
prod.Collection.Add(tester);
Upvotes: 1