Can You Spot the Bug? Lethal Combination
July 21. 2009
0 Comments
I blogged not too long ago about some stuffs that I was pondering…
Finally found out how one can get the “Object of type ‘System.Decimal’ cannot be converted to type ‘System.Int32’” error.
Given this code:
using System; using System.Data; using System.Data.SqlClient; using System.Collections.Generic; namespace ConsoleApplication1 { public class Foo { public int Id { get; set; } public int Number { get; set; } } class Program { static void Main(string[] args) { var foos = new List<Foo>(); var fooType = typeof(Foo); using (var cn = new SqlConnection(@"Server=.\SQLEXPRESS;Database=JimmyTest;Integrated Security=true")) { using (var cmd = cn.CreateCommand()) { cmd.CommandText = "SELECT * FROM dbo.[tablea] a INNER JOIN dbo.[tableb] b ON a.[BId] = b.[Id]"; cmd.CommandType = CommandType.Text; cn.Open(); using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) { var fieldCount = reader.FieldCount; while (reader.Read()) { var foo = new Foo(); for (var i = 0; i < fieldCount; i++) { var property = fooType.GetProperty(reader.GetName(i)); if (property != null) { property.SetValue(foo, reader.GetValue(i), null); } } foos.Add(foo); } } } } Console.ReadLine(); } } }
And this database:
USE master GO CREATE DATABASE JimmyTest GO USE JimmyTest GO CREATE TABLE tablea (Id int, BId int, Number int) GO CREATE TABLE tableb (Id int, Number decimal(10,2)) GO INSERT INTO tablea VALUES(1, 1, 100) INSERT INTO tablea VALUES(2, 2, 50) GO INSERT INTO tableb VALUES(1, 33.33) INSERT INTO tableb VALUES(2, 15.23) GO
Can you spot the bug?
Found it in the wild while troubleshooting one of my clients’ code.
Hint: Greed is one of the seven deadly sins. It’s pure evil!