DataContext.ExecuteQuery(CustomType, Query) returns IEnumerable of initialized CustomType

987 Views Asked by At

I need to execute runtime defined SQL queries on a database and show results on a datagrid. I'm using this code to query the database. It should return an IEnumerable of runtime defined objects of customType

List<dynamic> result;
using (context = new DataContext(ConnStr))
{
   IEnumerable enumerable = context.ExecuteQuery(customType, query);
   result = enumerable.Cast<dynamic>().ToList();
}

The sample customType and Query I'm using are as follows

CustomType: CustomType is created at runtime and it's equivalent to:

class customType 
{
 public int Id {get; set;}
}

Query:

Select id from TestTable

What ExecuteQuery is returning a list of customType objects that id is 0 in all of them. I did the same with context.ExecuteQuery and this time I defined my customType in compile time (<> operator does not work with Type instances), and it worked as expected and returned list of legit ids. I checked msdn page and find this interesting description:

Public method ExecuteQuery(String, Object[]) Executes SQL queries directly on the database and returns objects.

Public method ExecuteQuery(Type, String, Object[]) Executes SQL queries directly on the database.

Any help is appreciated.

Update: TestTable definition in my SQL Server database:

CREATE TABLE [dbo].[TestTable](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [StartDate] [datetime] NOT NULL,
    [BasePath] [varchar](512) NOT NULL,

 CONSTRAINT [PK_TestTable] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

(if there's any syntax error it's a typo)

0

There are 0 best solutions below