0

In my model, I have a handful of properties that occur on multiple types. For example, many types have a CreatedByUserId and CreatedDate. Types that can be updated have a LastUpdatedByUserId and LastUpdatedDate.

My first thought is to use Complex Types to encapsulate these fields to make my mappings easier. However, as noted below, Complex Types cannot have navigation properties, so no CreatedByUser on my entity.

EF-Code first complex type with a navigational property

EF4 complex type with navigation property (is it possible) or alternatives?

One option is it use base classes, but now I need 3, CreatedBy only, LastUpdatedBy only, and both. Not to mention this is one of several scenarios, which could lead to a very large number of base classes and that just feels wrong.

Do I just bite the bullet and define these properties on each type? Is there a better way to handle this?

Community
  • 1
  • 1
cadrell0
  • 17,109
  • 5
  • 51
  • 69
  • Here is a method that works for us: http://www.toplinestrategies.com/blogs/entity-framework-set-common-entity-fields-savechanges – Steve Greene Jul 02 '15 at 19:37
  • @SteveGreene That looks like a really good pattern. Unfortunately, what I'm trying to do doesn't just apply to tracking fields. I was just using that as a simple example that everyone could understand. – cadrell0 Jul 02 '15 at 19:42

1 Answers1

0

Create a class to inherit from The following will put the properties in BasicBO in the MyClass1s and MyClass2s tables.

public class Model1Context : DbContext
{
    public Model1Context()
        : base("name=Model1")
    {
        Database.SetInitializer(new Model1Initializer());
    }
    public virtual DbSet<MyClass1> MyClass1s { get; set; }
    public virtual DbSet<MyClass2> MyClass2s { get; set; }
}
public class Model1Initializer : DropCreateDatabaseIfModelChanges<Model1Context>
{
}
public class MyClass1 : BasicBO
{
    public string MyClass1Stuff { get; set; }
}
public class MyClass2 : BasicBO
{
    public string MyClass2Stuff { get; set; }
}
public class BasicBO
{
    public int Id { get; set; }
    public virtual User CreatedByUser { get; set; }  // or whatever
}
Kirsten
  • 15,730
  • 41
  • 179
  • 318