First let me start by saying that I don’t have a complete understanding of Linq. I am trying to dynamically query a database, The first query uses LINQ-SQL which works fine, but the second dynamic call is what fails in run time
public void getTables()
{
foreach (var c in dc.GetTable<TableListing>())
{
List<TableData> res = tableBrowse(c.TableName);
}
}
public List<TableData> tableBrowse(string tablename)
{
string sql = "Select * from " + tablename;
var results = dc.ExecuteQuery<TableData>(sql);
return results.ToList();
}
public class TableData
{
public int Time { get; set; }
public string Value { get; set; }
}
I query the “master table” and this retrieves a list of tables to query. They all have the same structure, as defined in the class TableData. I get a runtime error about Specified cast is not valid. I’m not really looking for code as much as I am looking for what I am doing wrong and how to fix it. Thanks.
You aren’t explicitly converting the return value from
dc.ExecuteQuery<TableData>(sql)to theTableDatatype that you’ve defined. I expect that the ExecuteQuery is complaining because it doesn’t know what theTableDatatype is.The
ExecuteQueryhelper needs to return a DBML (LINQ-to-SQL generated) type as defined in your database.But I would suggest that you don’t go down this route. If you want to get records from a table, say Customers, just use
content.Customers– the point of LINQ-to-SQL is that it already contains all these accessors to save you time.