Using Entity Framework 4 I want to create a base interface for my objects so that the properties of the base interface are implemented as fields in the table for each derived class (and not in its own table), and then deal with derived classes using the interface.
For example, you have an interface and some classes:
public interface IBaseEntity { public DateTime CreatedOn { get; set; } public string CreatedBy { get; set; } } public class SomeEntity : IBaseEntity { public int SomeEntityId { get; } public string Name { get; set; } public DateTime CreatedOn { get; set; } public string CreatedBy { get; set; } } public class OtherEntity : IBaseEntity { public int OtherEntityId { get; } public float Amount { get; set; } public DateTime CreatedOn { get; set; } public string CreatedBy { get; set; } }
This will result in two tables in the database: SomeEntity and OtherEntity, which will each have four fields. SomeEntity has SomeEntityId, Name, CreatedOn and CreatedBy, and OtherEntity has OtherEntityId, Amount, CreatedOn, and CreatedBy. There is no IBaseEntity table.
I would expect to see this in the designer, since IBaseEntity is an abstract object with its own CreateOn and CreatedBy properties and two specific objects that have only their non-derived properties, so SomeEntity has only SomeEntityId and Name. There is a relationship of inheritance between specific objects and an abstract entity.
Then I would like to have automatic column updates for these objects when they are saved, for example:
namespace MyModel { public partial class MyEntities { partial void OnContextCreated() { this.SavingChanges += new EventHandler(OnSavingChanges); } private static void OnSavingChanges(object sender, EventArgs e) { var stateManager = ((MyEntities)sender).ObjectStateManager; var insertedEntities = stateManager.GetObjectStateEntries(EntityState.Added); foreach (ObjectStateEntry stateEntryEntity in insertedEntities) { if (stateEntryEntity.Entity is IBaseEntity) { IBaseEntity ent = (IBaseEntity)stateEntryEntity.Entity; ent.CreatedBy = HttpContext.Current.User.Identity.Name; ent.CreatedOn = DateTime.Now; } } } } }
I'm just starting out with the Entity Framework, and it looks like it should be done pretty easily, but how to really implement it eludes me. Am I ok from here or is this possible in Entity Framework 4? The Table Per Concrete Type strategy looks like a solution, but I couldn’t get it working.