LINQPad在C#查询中创建SQLite数据库

3
LINQPad的IQ Connection插件可以使用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();
}
1个回答

3

只需将查询语言下拉菜单设置为“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# ExpressionC# Statements并开始使用适当的查询语言进行查询 :)

我希望能将所有内容合并到一个.linq文件中,这样就不需要在sqlite数据库不存在时进行修改。但我知道我要求太多了 :) - Thymine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接