Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 4.1, Code-First: Is there an easy way to remove ALL conventions?

We can remove single conventions this way:

modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<ConcurrencyCheckAttributeConvention>();
// and 31 conventions more

But I miss something like modelBuilder.Conventions.RemoveAll(). Is there an easy way to remove ALL of them?

(I am even not sure if I really want to remove all conventions finally. But with my growing object model I have difficulties to distinguish clearly which parts of the mapping to the DB come from conventions and which parts I have indeed configured explicitely in the Fluent API. I think currently I have a mix of pure convention based mapping, explicitely overwritten conventions and explicitely reproduced conventions. At least for learning purposes and clean understanding of the mapping it would be nice to be able to switch off ALL conventions.)

like image 374
Slauma Avatar asked Mar 20 '11 18:03

Slauma


1 Answers

I just create some solution with reflection:

public class Context : DbContext
{
    private static IList<Type> _types = typeof(IConvention).Assembly.GetTypes()
        .Where(t => !t.IsAbstract && t.IsClass && 
                    typeof(IConvention).IsAssignableFrom(t))
        .ToList();

    private static MethodInfo _method = 
        typeof(ConventionsConfiguration).GetMethod("Remove");

    // DbSets ...

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        foreach (var type in _types)
        {
            MethodInfo method = _method.MakeGenericMethod(type);
            method.Invoke(modelBuilder.Conventions, null);
        }
    }
}
like image 197
Ladislav Mrnka Avatar answered Sep 30 '22 18:09

Ladislav Mrnka