Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract domain model base class when using EntityTypeConfiguration<T>

Is there some trick to getting a central mapping of Base object properties? Is there some simple pattern for abstract classes when using EntityTypeConfiguration.
ANy tips much appreciated. Im unable to declare a class

Public class BaseEntityConfig<T> : EntityTypeConfiguration<T>

Similar issues, where i couldnt get the answers to work How to create and use a generic class EntityTypeConfiguration<TEntity> and Dynamic way to Generate EntityTypeConfiguration : The type 'TResult' must be a non-nullable value type

public  abstract class BosBaseObject
{
  public virtual Guid Id { set; get; }
  public virtual string ExternalKey { set; get; }
  public byte[] RowVersion { get; set; }
}
  public class News : BosBaseObject
{
    public String Heading { set; get; }
}


public class NewsMap : EntityTypeConfiguration<News>
{
    public NewsMap()
    {
      //Base Object Common Mappings
      // How can we use a central mapping for all Base Abstract properties  


     }
 }
// Something like this but very open to any suggestion....
public class BosBaseEntityConfig<T> : EntityTypeConfiguration<T>
{
  public void BaseObjectMap( )
    { 
        // Primary Key
        this.HasKey(t => t.Id);

        // Properties
        this.Property(t => t.Id).HasDatabaseGeneratedOption(databaseGeneratedOption: DatabaseGeneratedOption.None);

        this.Property(t => t.RowVersion)
            .IsRequired()
            .IsFixedLength()
            .HasMaxLength(8)
            .IsRowVersion();

        //Column Mappings
        this.Property(t => t.Id).HasColumnName("Id");
    }
}
like image 657
phil soady Avatar asked Nov 18 '12 05:11

phil soady


1 Answers

The answer above definitely works, though this may be slight cleaner and has the advantage of working the same when registering the configurations in the DbContext.

public abstract class BaseEntity
{
    public int Id { get; set; }
}

public class Company : BaseEntity
{
    public string Name { get; set; }
}

internal class BaseEntityMap<T> : EntityTypeConfiguration<T> where T : BaseEntity
{
    public BaseEntityMap()
    {
        // Primary Key
        HasKey(t => t.Id);
    }
}

internal class CompanyMap : BaseEntityMap<Company>
{
    public CompanyMap()
    {
        // Properties
        Property(t => t.Name)
            .IsRequired()
            .HasMaxLength(256);
    }
}

public class AcmeContext : DbContext
{
    public DbSet<Company> Companies { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new CompanyMap());
    }
}

Above solution arrived at by Christian Williams and myself early one morning...

like image 65
Mac Avatar answered Oct 08 '22 05:10

Mac