Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.