Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create table with Linq to Sqlite (linq2db)

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?

like image 640
マルちゃん だよ Avatar asked May 31 '13 08:05

マルちゃん だよ


People also ask

Can you use LINQ with SQLite?

LinqConnect is a lightweight, LINQ to SQL-compatible ORM solution with support for SQLite, Oracle, PostgreSQL, and SQLite.

What is linq2db?

linq2db - LINQ to DB is the fastest LINQ database access library offering a simple, light, fast, and type-safe layer between your POCO objects and your database.

How many tables can you create with SQLite?

Maximum Number Of Tables In A Join SQLite does not support joins containing more than 64 tables. This limit arises from the fact that the SQLite code generator uses bitmaps with one bit per join-table in the query optimizer.


1 Answers

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.

like image 99
Andrey Efimov Avatar answered Sep 23 '22 18:09

Andrey Efimov