We are using Net Core 2 with Entity Framework. Our Sql database consists of many tables, Address, Account, Customer, Sales, etc.
Some tables have corresponding history tables: AddressHistory, CustomerHistory,
Anytime someone changes something in original tables, the corresponding History table should be updated. (cannot use sql temporal tables, since we have custom history logic)
We are trying to apply interfaces, I'm little stuck on the code, can someone provide a quick code example of how to implement this with interfaces? Especially in SaveHistory portion, how can dependency injection be applied? Feel free to rewrite code as needed
public partial class TestDbContext
{
public void AddEntityHistory<IEntityHistory>(IEntityHistory entity) where IEntityHistory: Address
{
// do something 1 etc
}
public void AddEntityHistory<IEntityHistory>(IEntityHistory entity) where IEntityHistory: Customer
{
// do something 2 etc
}
public override int SaveChanges()
{
SaveEntityHistory();
return base.SaveChanges();
}
protected void SaveEntityHistory()
{
var modifiedEntities = ChangeTracker.Entries<IEntityHistory>().Where(e => e.State == EntityState.Added || e.State == EntityState.Modified);
foreach(var entity in modifiedEntities)
{
AddEntityHistory(entity); // what is the code base here? giving error below, it should call appropriate AddEntityHistory Method for corresponding Entity
}
}
}
Error Above:
Error CS0311 The type 'Interfaces.IEntityHistory' cannot be used as type parameter 'IEntityHistory' in the generic type or method 'PropertyContext.AddEntityHistory(IEntityHistory)'. There is no implicit reference conversion from 'Interfaces.IEntityHistory' to 'Data.Entities.Address'.
Resources :
Trying to utilize similar codebase: for CreateDate, UserId, etc
https://dotnetcore.gaprogman.com/2017/01/26/entity-framework-core-shadow-properties/