Question

I am using wcf rest service. I am querying sql server database to return me rows from the table name which i pass from GUI. What happens is that sometimes table doesnt exist in database and i am using singleorDefault method of Linq. So if there is no table in database then it throws exception. How could i handle this? I still need to perform certain logic even if table is not found. Here is my code

var strTableQuery = "Select * from " + tableName // i get this tableName from my GUI

Tables = Context.Database.SqlQuery<TableClass>(strTableQuery );  
var x = Tables.SingleorDefault(); // i get exception on this line

if (x != null){
    // do some logic
} else {
    //do some logic
}

Update1 I get exception as Invalid object name tableName

Was it helpful?

Solution

Fire this query before and check if your table exists or not.

SELECT count(*) FROM INFORMATION_SCHEMA.TABLES  WHERE TABLE_SCHEMA = 'SomeSchema' AND  TABLE_NAME = 'someTable'

Update

Create a table called as Table_Existing_In_Your_Schema(name varchar, create_on datetime);

Load this table in a static dictionary in your global.asax.cs

Dictionary<string, DateTime> _allTablesCollection;

Writing a common module (something like dal) to fire all your query. In this module, before firing query

if(!_allTablesCollection.keys.Contains("someTable"))
     createTable("someTable");
     update_the_dictionary_with_this_key

//now fire your query
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top