2011-11-17 88 views
2

允許使用SQLite的LINQPad的IQ Connection插件有一個「創建數據庫如果丟失」的複選框,但只會創建一個空文件。無論如何,當文件不存在時自動構建表格?LINQPad在C#查詢中創建sqlite數據庫

不應該有辦法獲得DataContext並使用該接口創建表嗎?希望導致LINQPad同時更新其DataContext。

我已經能夠到目前爲止做的是下面的最好的,創造DbCommands和刪除SQLite的文件後執行他們在第一次運行,那麼我必須刷新數據庫,並重新運行。

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(); 
} 

回答

2

只需設置查詢語言下拉菜單「SQL」,鍵入DDL,然後按F5。例如:

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 
) 

(注創建外鍵約束的語法。)

一旦您完成後,用鼠標右鍵單擊架構資源管理的連接,並選擇「刷新」。然後,您可以切換查詢語言回C#表達C#聲明,並開始:)

+0

我希望我能擁有這一切組合成一個.linq文件正確的查詢語言查詢該不會需要修改任何時候sqlite數據庫不存在。但我知道我在那裏問很多:) – Thymine