EF 4.1,code-第一:有一种简单的方法来消除所有公约?有一种、公约、方法来、简单

2023-09-02 20:49:18 作者:萌着萌着就懵了

我们可以删除一个约定是这样的:

We can remove single conventions this way:

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

不过,我想是这样 modelBuilder.Conventions.RemoveAll()。有一个简单的方法来消除所有这些吗?

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

(我甚至不知道如果我真的要最终消除所有约定。但随着我的成长对象模型我有困难,要区分清楚其映射到数据库的部分来自公约和部分我确实明确地配置在良好的API中。目前,我想我有纯粹的约定为主映射,明确地覆盖公约和显式地再现约定的混合体。至少对于学习的目的和清洁的理解映射,这将是很好能够关掉的所有公约。 )

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

推荐答案

我刚刚创建与反思一些解决方案:

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