6

What I'm trying to do is to create a table on the fly, when a connection is opened on an empty database. I've already created the model with Linq to Sqlite and successfully used it with non-empty databases.

Now I'm trying to work with "new" databases.

I do my db.Insert like this:

    using (MyDB db = MyDB("MyConnectionName"))
    {
            Person d = new Person()
            {
                name = "mimi"
            };

            db.Insert(d);

            myLabel.Content = db.Drivers.First().name;
        }
    }

An empty database is opened OK. Actually a 0KB file is created for it. But when I try to insert something into it (or of course read something) I get an exception: SQL logic error or missing database

The library I'm using:

https://github.com/linq2db/linq2db

The NuGet package:

http://nuget.org/packages/linq2db.SQLite/

Is there something I need to do before start writing to an empty database file?

1
  • 2
    Don't know anything about linq2db, but not every linq provider will support creating of data tables. You may have to either ship a empty database, or create the tables using TSql 'Create table' commands. Commented Jun 1, 2013 at 13:22

3 Answers 3

16

Linq2DB doesn't create tables automatically. So you have to check whether table exists and if not-create it. You can do it this way:

    var sp = db.DataProvider.GetSchemaProvider();
    var dbSchema = sp.GetSchema(db);
    if(!dbSchema.Tables.Any(t => t.TableName == "Person"))
    {
       //no required table-create it
       db.CreateTable<Person>();
    }

Unfortunately there is some lack of documentation. But you can use test sample.

Sign up to request clarification or add additional context in comments.

Comments

5

To expand upon Andrey Efimov's answer, rather than implementing your own query to the schema to see if the table exists and conditionally creating the table, there is a built in property to only create the table if its necessary.

connection.CreateTable<MyEntity>(tableOptions: TableOptions.CheckExistence);

Comments

-4

you don't open the database.

MyDB db = MyDB("MyConnectionName") <- Create Database.

db.open(); <- add this.

then you will operate ordinarily.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.