Unit Test to verify Entity Framework Model (EDMX) is accurate

I work extensively with the Entity Framework in most of my projects. One thing that gets frustrating though is when you work with a large team and the data model gets out of synch with your local database.

You normally don’t figure it out until you are running some operation in your application and get the dreaded Entity Framework error. (inner exception = Column Missing), or non-nullable type, or other enjoyable light reading.

I put together a simple unit test that will work with any model and verify it using a very simplistic technique. It’s a quick smoke test.


You will need to modify this code to fit your mechanics for creating the entity context, and the connection strings, etc. Other than that, it is shake and bake.

        public void VerifyModelAccuracy()
            //FYI – When switching to multiple engagements, will need to pass in engagement id for db connection (get from routing db)
            using (var context = EngagementContextFactory.CreateEngagementContext())
                //lazy and dont want to research why this isnt loading
                //use reflection to iterate over each collection in the context and just watch for errors.

                Type t = context.GetType();
                var props = t.GetProperties();
                foreach (var p in props)
                    var isEnumerable = (from i in p.PropertyType.GetInterfaces()
                                        where i == typeof(IEnumerable)
                                        select i
                                            ).Count() > 0;
                    if (isEnumerable)
                            IEnumerable dataToPull = (IEnumerable)p.GetValue(context,null);
                            if (dataToPull != null)
                                var result = (from object d in dataToPull select d).FirstOrDefault();
                        catch (Exception ex)
                            string error = ex.Message;
                            if (ex.InnerException != null)
                                error += ex.InnerException.Message;
Happy Coding!!

Join the Conversation

No comments

  1. The topic of this blog is so useful…This is popular to us..THANK YOU FOR SHARING THIS BLOG!!:d

  2. This is an excellent Test to verify the model of entity framework against the DB – I just need to figure out how to extend it to functional imports and stored procedure signatures to completely protect my apps from well meaning ‘support fixes’.

    Thanks very much for posting

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.