【问题标题】:How can I detect if an Entity Framework Migration broke my SQL View?如何检测实体框架迁移是否破坏了我的 SQL 视图?
【发布时间】:2016-04-01 14:28:06
【问题描述】:

我有很多表,一些查询是由 SQL 视图提供的。

我不希望制造维护噩梦,开发人员首先更改代码中的列,导致一个或多个 SQL 视图中断。

EF 中是否有机制来检查这一点?

【问题讨论】:

    标签: sql-server entity-framework entity-framework-6 entity-framework-migrations sql-view


    【解决方案1】:

    视图是否在 EF 中映射?
    通常我会运行一个 EF 配置测试来检查所有表。
    我还发布了主代码,但它仅在主键包含一个且只有一个名为 Id 的属性时才有效。你可以调用 FirstOrDefault 方法来修复它(你可以在这里查看如何调用它 How do I use reflection to call a generic method? )。

    [TestMethod]
    public void All()
    {
    
        var properties = typeof (Context).GetProperties().Where(p => IsSubclassOfRawGeneric(typeof(DbSet<>), p.PropertyType));
    
        foreach (PropertyInfo property in properties)
        {
            Type entityType = property.PropertyType.GetGenericArguments()[0];
            PropertyInfo idProperty = entityType.GetProperty("Id");
            if (idProperty == null)
            {
                Console.WriteLine("Id property not found. Cannot check type configuration");
                continue;
            }
            Type idPropertyType = idProperty.PropertyType;
            DbSet dbSet = _context.Set(entityType);
            if (idPropertyType == typeof(string))
            {
                try
                {
                    dbSet.Find("A");
                }
                catch (Exception e)
                {
                    throw new Exception("Cannot access to DbSet " + property.Name, e);
                }
            }
            else if (idPropertyType == typeof (int))
            {
                try
                {
                    dbSet.Find(1);
                }
                catch (Exception e)
                {
                    throw new Exception("Cannot access to DbSet " + property.Name, e);
                }
            }
            else
            {
                Console.WriteLine("Id property type not supported ('{0}'). Cannot check type configuration", idPropertyType.Name);
                continue;
            }
    
        }
    
    }
    
    
    static bool IsSubclassOfRawGeneric(Type generic, Type toCheck)
    {
        while (toCheck != null && toCheck != typeof(object))
        {
            var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
            if (generic == cur)
            {
                return true;
            }
            toCheck = toCheck.BaseType;
        }
        return false;
    }
    

    【讨论】:

      【解决方案2】:

      不,没有。为什么代码优先迁移只是一个玩具,而不是一个工具。

      与在 SSDT 环境中维护数据库并手动生成和验证更改脚本进行比较。当您使用任何非基线功能(并且这些功能很有用)时,迁移会更快地变成“加载 SQL 脚本并执行它们”。

      所以,不。

      您可以做的是进行单元/集成测试,自动测试应用程序在上次迁移时的工作情况。自动化测试助您一臂之力。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-19
        • 2015-05-11
        相关资源
        最近更新 更多