使用Linq to Sqlite创建表(linq2db) [英] Create table with Linq to Sqlite (linq2db)

查看:688
本文介绍了使用Linq to Sqlite创建表(linq2db)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要执行的操作是在空数据库上打开连接时动态创建table.我已经用LinqSqlite创建了模型,并将其成功地用于非空数据库.

现在,我正在尝试使用新"数据库.

我这样做是db.Insert:

    using (MyDB db = MyDB("MyConnectionName"))
    {
            Person d = new Person()
            {
                name = "mimi"
            };

            db.Insert(d);

            myLabel.Content = db.Drivers.First().name;
        }
    }

打开一个空数据库,确定.实际上为它创建了一个0KB的文件.但是,当我尝试向其中插入某些内容(或当然要读取某些内容)时,出现异常:SQL logic error or missing database

我正在使用的图书馆:

https://github.com/linq2db/linq2db

NuGet软件包:

http://nuget.org/packages/linq2db.SQLite/

在开始写入一个空的数据库文件之前,我需要做些什么吗?

解决方案

Linq2DB不会自动创建表.因此,您必须检查表是否存在,如果不存在,请创建它.您可以这样操作:

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

不幸的是,缺少一些文档.但是您可以使用测试样本.

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?

解决方案

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.

这篇关于使用Linq to Sqlite创建表(linq2db)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆