DateTimePicker Control Data Type Mismatch Problem

A reader recently made me aware of a problem with the Get User Favorites example in Chapter 2 that could cause a lot of problems depending on which language you use when working with Visual Studio 2012. This issue does affect some of the examples in Microsoft ADO.NET Entity Framework Step by Step so it’s really important you know about it.

Look at the model on page 30 of the book (the “Creating the model” section of Chapter 2). The Birthday field is defined as type DateTime. When you finish creating the model, you right click the resulting entity and choose Generate Database from Model to create a database from it. The “Working with the mapping details” section of Chapter 1 (page 19) tells you how to use the Generate Database Wizard to create the database. The Birthday field in the database will appear as a datetime type when you complete the wizard, which is precisely what you should get.

At this point, you begin creating the example form to test the database (the “Creating the test application” section on page 36). The example uses a DateTimePicker control for the Birthday field by default. You don’t add it, the IDE adds it for you because it sees that Birthday is a datetime data type. The example will compile just fine and you’ll be able to start it up as normal.

However, there is a problem that occurs when working with certain languages when you start the “Running the basic query” section that starts on page 39. The DateTimePicker control appears to send a datetime2 data type back to SQL Server when you change the birthday information. You’ll receive an exception that says the data types don’t match, which they don’t. There are several fixes for this problem. For example, you could coerce the output of the DateTimePicker control to output a datetime data type instead of a datetime2 data type. However, the easiest fix is to simply change the data type of the Birthday field in the database from datetime to datetime2. After you make this change, the example will work as it should. You only need to make this change when you see the data type mismatch exception. I haven’t been able to verify as of yet which languages are affected and would love to hear from my international readers about the issue.

As far as the book is concerned, this problem is quite fixable using the manual edit (although, manually editing the database shouldn’t be something you should have to do). However, it does bring up the question of how teams working across international boundaries will interact with each other if they can’t depend on the controls acting in a particular way every time they’re used. This is a problem that you need to be aware of when working with larger, international, teams. Let me know if you have any questions or concerns about the book example at John@JohnMuellerBooks.com. You’ll have to contact Microsoft about potential fixes to the DateTimePicker control since I have no control over it.