Seeing produced code and debugging Entity Framework

Everyone had the problem when you hit a brick wall and then you needed to use something more to debug the program that was working  in very weird and unexplainable way. Today i had one of those problems and I want to share solution to it.




I have table in database which has very simple structure consisting of 2 columns. One column holds ID when the other holds name of the holded ID. I created automatic class which mapped my enum to entities and uploaded it to database when given ID was not present in database.

Everything looks very good. Those are all properties of the VotingType. But something bizarre happened when SaveChanges was called:

But….but..why? I had supplied my entity with ID. Why the heck I have problem with NULL ID? As we will see the answer to the problem will be very simple but I needed to debug this one to know where the problem is.


So I did not completely know how to resolve problem so I needed to debug my SQL Code. I Launched SQL Server Profiler and created new Trace to show me what SQL is generated by program. Before starting trace it’s good idea to filter user name in Events Selection tab when you create your trace. You do so by clicking on Column Filters… button

With it you will only see SQL generated directly by your user.

My SQL looked exactly like this:

I was shocked. Entity Framework wanted to generate my ID automatically. I checked database and I had identity turned off.

Then i knew the culprit…. I did not disabled identity in my .edmx file. (Because previously i had auto ID generation turned on)

Some wise words

I should say some wise words like ‘always check your .edmx file before debugging’ or something like that. But in reality every debugging case is unique and we cannot have pack of wise words to solve problems by us. But the more problems we see the easier it gets to solve new ones in future because during our debugging fights we find new tools to help us diagnose problems.

Leave a Reply

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