【问题标题】:LINQPad create sqlite database in C# queryLINQPad 在 C# 查询中创建 sqlite 数据库
【发布时间】:2011-11-17 02:04:13
【问题描述】:

允许使用 SQLite 的 LINQPad 的 IQ Connection 插件有一个“如果丢失则创建数据库”复选框,但这只会创建一个空文件。文件不存在时是否自动建表?

不应该有一种方法来获取 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();
}

【问题讨论】:

    标签: sqlite linqpad


    【解决方案1】:

    只需将查询语言下拉菜单设置为“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 数据库不存在,就不需要修改该文件。但我知道我在那里问了很多:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2013-02-03
    • 2019-01-14
    相关资源
    最近更新 更多