1

I am using Entity Framework in .NET MVC with C#. I've made an interface for POCOs whom I want to track their changes to (custom logic based on POCO, not what EF can already do). The interface:

public interface ITrackChangesService<TClass>
    {
        void SaveChanges(TClass entity);
    }

I am trying to have this be used in my EntitySevice which all POCO services inherit from, the declaration of EntityService:

 public abstract class EntityService<TRepositoryClass, TClass, TDbContext>
    where TClass : Entity, new()
    where TDbContext : DbContext, new()
    where TRepositoryClass : EntityRepository<TClass, TDbContext>, new()
{

As my comments show, I am trying to check if when Save is called from a subclass such as UserService:

public class UserService : EntityService<UserRepository, User, MyDbContext>, ITrackChangesService<User>

To see if the UserService implements ITrackChangesService and if so, call the SaveChanges method on it. This is being done in my Save method in entity service:

public virtual void Save(TClass entity)
    {
        if (entity != null)
        {
            entity.LastModifiedBy = SessionUtil.UserAbsolute == null ? "System" : SessionUtil.UserAbsolute.NetId;

            if (Exists(entity))
            {
                entity.DateModified = DateTime.Now;
                //if(this is ITrackChangesService<TClass>)
                //{
                //    (ITrackChangesService<TClass>) this.SaveChanges(entity);
                //}
                Repository.Update(entity);
            }
            else
            {
                entity.CreatedBy = SessionUtil.UserAbsolute == null ? "System" : SessionUtil.UserAbsolute.NetId;
                entity.DateCreated = DateTime.Now;
                Repository.Insert(entity);
            }
        }
    }

However I can't seem to be able to call the SaveChanges method off the calling subclass. .SaveChanges is not recognized. How do I get that to be recognized.

Jared Dykstra
  • 3,596
  • 1
  • 13
  • 25
SventoryMang
  • 10,275
  • 15
  • 70
  • 113
  • 1
    BTW unrelated but using `DateTime.Now` instead of `UtcNow` is nearly always a bad idea when databases are concerned. – Ian Mercer Nov 13 '15 at 21:07
  • Actually (in addition to what @IanMercer said) you may want to wrap `DateTime.UtcNow` in an injectable type so you can test your date logic on any date (by injecting either the real date/time or by injecting a specific fake date). – xxbbcc Nov 13 '15 at 21:13

1 Answers1

4

You're casting the return value of this.SaveChanges() instead of this.

var trackChangesService = this as ITrackChangesService<TClass>;
if(trackChangesService != null)
{
    trackChangesService.SaveChanges(entity);
}
Jared Dykstra
  • 3,596
  • 1
  • 13
  • 25