Created
October 11, 2017 15:14
-
-
Save cosoria/c100277bda9e1253244ec8da3a205e7d to your computer and use it in GitHub Desktop.
EntityFrameworkContext is the class that dynamically loads its configuration from the assembly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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