EF CTP5 POCO, base class and how to implement inheritance

1k views Asked by At

Hey, lets say I want all my recordsto have a standard stamp on them.

inserted_by, inserted_at, updated_by, updated_at, deleted_by, deleted_at, timestamp

1 - If I had to put this in a base (maybe abstract) POCO class, what would be the best inheritance strategy to implement this. (I am using GUID as primary keys.)

I do not want to use base class for anything else. In my Db Context; I'd like to use the end POCO classes that corresponds to the db table. DbSet, looks like I have to use DbSet tough, then use OfType to query:)

2 - If Inheritance is out of context, what would you recommend, ComplexType, an Interface maybe?

2

There are 2 answers

6
JK. On

I do exactly that in EF4. There is a generic repository base class:

public class GenericRepository<T> : IGenericRepository<T> where T : BaseEntity

All entity repositories inherit from this class. The generic .Add() and .Update() method automatically set the audit data:

public void Add(T entity)
{
        entity.CreatedOn = DateTime.UtcNow;
        entity.CreatedBy = UserName;
        entity.LastModifiedOn = entity.CreatedOn;
        entity.LastModifiedBy = entity.CreatedBy;
        ObjectContext.AddObject(GetEntitySetName<T>(), entity);
}

public void Update(T entity)
{
        T originalEntity = ObjectSet.Single(t => t.Id == entity.Id);            
        entity.CreatedOn = originalEntity.CreatedOn;
        entity.CreatedBy = originalEntity.CreatedBy;
        entity.LastModifiedOn = DateTime.UtcNow;
        entity.LastModifiedBy = UserName;
        ObjectSet.ApplyCurrentValues(entity);
}

So you can see that it doesnt go into the POCO base class BaseEntity, because it's not the responsibility of the POCO. Instead it belongs to the Repository.

4
Ladislav Mrnka On

You need TPC inheritance (Table per class or Table per concrete type). Check this article about CTP5 mapping of TPC.