Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

.net - 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.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...