I have 2 POCO classes:
class Email: Base { public int SomeProperty { get; set; } } class Photo: Base { public int SomeOtherProperty { get; set; } }
and base class
abstract class Base { public DateTime DateCreated { get; set; } }
here is my context definition:
public class EntitiesContext : DbContext { public DbSet<Email> Emails { get; set; } public DbSet<Photo> Photos { get; set; } }
Of course, these classes are just for example, things are more complicated.
the base class is intended only for common properties for each changed table, state, etc. I believe that I am using the Table-Per-Type approach.
PROBLEM: I have a common business logic that I need to run against each table (for example, count the raw elements of each type). I need a way to iterate through a set of tables with a common base class. I was hoping to do something like this:
private void GoThroughAllTables(Action<DbSet<Base>> fnProcess, bool needSave) { using (var db = new EntitiesContext()) { fnProcess(db.Emails); fnProcess(db.Photos); if (needSave == true) { db.SaveChanges(); } } } public IEnumerable<QueueStatus> GetQueueStatus() { var res = new List<QueueStatus>(); GoThroughAllTables((set) => { res.Add(new QueueStatus { Count = set.Cast<Base>().Count(x => x.DateCreated > someDate), }); }, false); return res; } public void DeleteFailedItems() { GoThroughAllTables((set) => { set.Cast<Base>().Remove(x => x.DateCreated > someDate); }, true); return res; }
this will not compile:
fnProcess(db.Emails);
Argument 1: cannot be converted from 'System.Data.Entity.DbSet | Email | ' in 'System.Data.Entity.DbSet | Base | '
the transfer of non-printable DbSet will not work because Cast will fail.
so I'm not sure what else I can try. Any suggestions?
source share