Search code examples
linqwindows-phone-7exceptionsql-server-ce

Getting SqlCeException on restart if I don't insert data to the DB


Basically, I have a LINQ database context and its model. As usually, I create the DB in the SQL context if the DB does not exist (the context is a singleton and on every access to it, this is checked).

Everything works well if I add data to the DB on the first launch. But if I don't insert any data during the first start of the app, on successive launches I get

SqlCeException:The specified table does not exist [TableName]

I don't know how more specifically I can explain it, but the exception comes immediately whenever I do a LINQ query on the second launch of the app if I don't insert any data on the first launch. If i do insert some data during the first launch, all is fine for the rest of the app's life time. Why would it be a bad thing to create the DBs and introduce the DB context, but not insert any data?

Here's my LINQ DB model:

Here's where I get the exception on second start if I didn't insert any data on the first launch:

It also strikes me that there's no API call to check if a table exists or not in LINQ, so I would have to assume "this should just work" - but it doesn't.

Any ideas? Thanks! :)

Update: I verified analyzing the .sdf file that indeed there are no tables created if I don't insert any data upon first launch of the app. As I see it:

  • This is a bug in LINQ-to-SQL. It should not crash if there are no tables present, but know that it should create them. Or deal with the case and create tables only when data is inserted.
  • I would need to insert some dummy data into SQL always on first launch, or...
  • Check if a table exists, if not, react to it by forcing LINQ-to-SQL to create them. But how?

Solution

  • I've dealt with this problem also, I've fixed it this way:

    get the data context:

    dbDataContext = new DBDataContext(DBConnectionString);
    
    if( dbDataContext.DatabaseExists() == true)
    

    //then try to get an entity:

    System.Data.Linq.Table<Entity> entities = dbDataContext.Tablename;
    

    //try to get an element from the entity:

    IEnumerator<Entity> enumEntity = entities.GetEnumerator();
    

    entities.GetEnumerator(); will always raise the exception "Table not found."

    Just use a try/catch and in the catch scope delete the db and recreate it, because your DB is empty anyway :)

    dbDataContext.DeleteDatabase();
    dbDataContext.CreateDatabase();
    dbDataContext.SubmitChanges();