Skip to content

Instantly share code, notes, and snippets.

@cosoria
Created October 11, 2017 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cosoria/c100277bda9e1253244ec8da3a205e7d to your computer and use it in GitHub Desktop.
Save cosoria/c100277bda9e1253244ec8da3a205e7d to your computer and use it in GitHub Desktop.
EntityFrameworkContext is the class that dynamically loads its configuration from the assembly
public class EntityFrameworkContext<TContext> : DbContext, IEntityFrameworkContext where TContext : DbContext
{
public ObjectContext ObjectContext { get { return ((IObjectContextAdapter)this).ObjectContext; } }
protected EntityFrameworkContext() : base()
{
Database.SetInitializer<TContext>(null);
}
protected EntityFrameworkContext(string nameOrConnectionString) : base(nameOrConnectionString)
{
Database.SetInitializer<TContext>(null);
}
public IDbSet<TEntity> GetDbSetOf<TEntity>() where TEntity : class
{
return base.Set<TEntity>();
}
public void MarkAsAdded(object entity)
{
Entry(entity).State = DataEntityState.Added;
}
public void MarkAsModified(object entity)
{
Entry(entity).State = DataEntityState.Modified;
}
public void MarkAsDeleted(object entity)
{
Entry(entity).State = DataEntityState.Deleted;
}
public void MarkAsUnchanged(object entity)
{
Entry(entity).State = DataEntityState.Unchanged;
}
public void ExtendQueryTimeout()
{
ObjectContext.CommandTimeout = 180;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
LoadDynamicModelConfiguration(modelBuilder);
}
protected virtual void LoadDynamicModelConfiguration(DbModelBuilder modelBuilder)
{
foreach (var modelConfigType in GetDynamicModelConfigurationTypes())
{
dynamic modelConfig = Activator.CreateInstance(modelConfigType);
modelBuilder.Configurations.Add(modelConfig);
}
}
protected virtual IEnumerable<Type> GetDynamicModelConfigurationTypes()
{
var types = Assembly.GetAssembly(GetType())
.GetTypes()
.GetOpenGenericDecendants(typeof(DynamicEntityTypeConfiguration<>))
.Where(t => t.Namespace == GetType().Namespace);
return types;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment