Checking the EF data model at runtime (scheduling differences between EDMX and SQL database schema)

I would like to do a .NET Entity Framework sanity check on all existing Data Model objects and potentially stored procedures (against their representative database tables) when the application starts up. We are using Database First Approach, so changes are made using SQL scripts prone to manual execution errors.

This will allow me to identify any synchronization issues (especially after deployment) in a controlled manner (custom error handling). Provides greater confidence in deploying new versions and debugging problems faster.

In addition, this will be added to the self-diagnostic screen so that infrastructure personnel can check the health of the database at any time.

Any ideas how to do this? I cannot find a native EF mechanism for this, so it will fail if you use a buggy object that is unpredictable and can easily be overlooked.

+3


source to share


1 answer


Ok, so I couldn't find a build mechanism for this, so I had to use reflection to get all entities in the DB context and then individually try to retrieve FirstOrDefaut () in a try catch. This is not ideal, but it will give a higher level of confidence in alignment between the EDMX and the database.



public static List<Type> GetAllEntities()
{
    var entityList = new List<Type>();
    var context = typeof(<DatabaseContextClass>);

    foreach (var property in context.GetProperties())
    {
        if (!property.PropertyType.IsGenericType
            || property.PropertyType.GetGenericTypeDefinition() != typeof(ObjectSet<>)) // EF 4
            continue;

        var entityType = property.PropertyType.GetGenericArguements()[0];
        entityList.Add(entityType);

        return entityList;  
    }
}

public static T GetFirstObject<T>() where T : EntityObject
{
    var context = new <DatabaseContextClass>();

    IQueryable<T> = dbQuery = context.CreateObjectSet<T>();

    return dbQuery.AQsNoTracking().FirstOrDefault();
}

      

0


source







All Articles