c# - 如何清空 EntityFramework DbContext?

标签 c# .net entity-framework dbcontext

如何在不了解其内部对象和类型的情况下清空任意 DbContext? (删除数据库)

不幸的是,没有通用的方法可以做到这一点。但这很有用,即在针对本地测试数据进行测试时。

最佳答案

我能够通过以非常复杂的方式使用反射来解决这个问题。这看起来很奇怪,但事实上 C# 不支持像 Java<?> 这样的通用通配符。我们是否需要一个通用方法并通过反射调用它。当然,该解决方案执行速度很慢,但对于本地测试、调试和开发问题来说它足够快。

    public static void GenericRemoveSet<T>(System.Data.Entity.DbSet<T> set) where T:class
    {
        foreach (var item in set) set.Remove(item);
    }

    public static void ClearGenericDbContext(DbContext context)
    {
        var removeMethod = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.GetMethod("GenericRemoveSet");
        foreach (var prop in context.GetType().GetProperties().Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(System.Data.Entity.DbSet<>)))
        {
            var typedRemove = removeMethod.MakeGenericMethod(prop.PropertyType.GetGenericArguments().First());
            typedRemove.Invoke(null, new object[]{prop.GetValue(context)});
        }
        context.SaveChanges();
    }

关于c# - 如何清空 EntityFramework DbContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18214829/

相关文章:

c# - 分析 C# 和 mscorlib.ni.dll

c# - .NET 程序集绑定(bind),我可以将一个程序集映射到另一个程序集中的版本吗?

c# - 对测试失败+异常进行截图

c# - 使用 Array.Copy() 对数组内容进行自动类型转换

c# - list.add 似乎在添加对原始对象的引用?

c# - Delegate.CreateDelegate 不会将返回值装箱 - 是故意的,还是疏忽?

c# - 用泛型抽象一个类

c# - 如何在 Entity Framework 中获取数字字符串列的最大值

ios - 是否可以在 Monotouch/Xamarin 中实现 Entity Framework 的 Code First?

c# - c#中的字符串 vector