3

The IQ Connection plugin for LINQPad that allows one to use SQLite has a checkbox for "Create database if missing" but that will only create an empty file. Is there anyway to build the tables automatically when the file doesn't exist?

Shouldn't there be a way to get the DataContext and create tables using that interface? Hopefully causing LINQPad to update its DataContext at the same time.

The best I've been able to do so far is below, creating DbCommands and executing them on the first run after deleting the sqlite file, then I have to refresh the database, and run it again.

void Main()
{
    if (!File.Exists(this.Connection.ConnectionString.Split('=')[1]))
    {
        "CREATING DATABASE TABLES".Dump();
        CREATE_TABLES();
    }
    else
    {
        "RUNNING CODE".Dump();
        //Code goes here...
    }
}

public void CREATE_TABLES()
{
    this.Connection.Open();
    System.Data.Common.DbCommand sup = this.Connection.CreateCommand();
    sup.CommandText = @"create table MainTable
(
    MainTableID INTEGER not null PRIMARY KEY AUTOINCREMENT,
    FileName nvarchar(500) not null
)";
    sup.ExecuteNonQuery();
    sup.CommandText = @"create table SubTable
(
    SubTableID int not null,
    MainTableID int not null,
    Count int not null,
    primary key (SubTableID, MainTableID),
    FOREIGN KEY(MainTableID) REFERENCES MainTable(MainTableID)
)";
    //Apparently this version of sqlite doesn't support foreign keys really
    sup.ExecuteNonQuery();
    this.Connection.Close();
}

1 Answer 1

3

Just set the query language dropdown to 'SQL', type in the DDL and hit F5. For instance:

PRAGMA foreign_keys = ON
GO

create table Customer
(
    ID int not null primary key,
    Name nvarchar(30) not null
)
GO

create table Purchase
(
    ID int not null primary key,
    CustomerID int null references Customer (ID),
    Date datetime not null,
    Description varchar(30) not null,
    Price decimal not null
)

(Note the syntax for creating foreign key constraints.)

Once you're done, right-click the connection in the Schema Explorer and choose 'Refresh'. You can then switch the query language back to C# Expression or C# Statements and start querying in a proper query language :)

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

1 Comment

I was hoping that I could have it all combined into one .linq file that wouldn't need modifying anytime the sqlite database doesn't exist. But I know I'm asking a lot there :)

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.