【问题标题】:SQLite doesn't know about classSQLite 不知道类
【发布时间】:2018-08-29 06:41:38
【问题描述】:

我目前正在开发一个 Windows 窗体应用程序,我想使用一个不需要后备服务器或凭据即可运行的简单数据库,因此我选择了 SQLite。但到目前为止,试图让这件事发挥作用是一场噩梦。

现在,我有一些具有简单属性的简单类,我想将它们存储在数据库中。我已经为所有内容添加了适当的标签([Table("")] 用于类,[PrimaryKey, AutoIncrement] 用于 Id 属性),但每当我执行Connection.CreateTable(CreateFlags.AutoIncPK) 时(它不会显示通用参数,但它就在那里,我保证),它抛出一个 NotSupportedException,说“不知道 MyProject.MyClass”。我还在每个类中提供了一个空的、无参数的构造函数。

那么,我如何让 SQLite “了解”我的班级?

编辑: 我的 Character.cs 文件:

[Table("Character")]
class Character
{
    [PrimaryKey, AutoIncrement]
    public int id { get; set; }

    public string Name
    {
        get;
        set;
    }
    public string FilePath
    {
        get;
        set;
    }
    public Character()
    {
    }
    public Character(string file)
    {
        this.FilePath = file;
        this.Name = FetchName(file);
    }

    private string FetchName(string file)
    {
        string[] fileHolder = File.ReadAllLines("\\chars\\" + file);
        foreach (string line in fileHolder)
        {
            if (line.ToLower().StartsWith("name"))
            {
                if (!line.Contains(';'))
                    return line.Split('=')[1].Trim().Trim('"');
                else return line.Split('=')[1].Split(';')[0].Trim().Trim('"');
            }
        }
        return string.Empty;
    }
}

我的 Database.cs 文件:

class Database
{
    private static SQLiteConnection Connection;
    private static string ConnectionString = "MyProject.sqlite";
    public Database()
    {
        if (!File.Exists("MyProject.sqlite"))
            System.Data.SQLite.SQLiteConnection.CreateFile("MyProject.sqlite");
        using (Connection = new SQLiteConnection(ConnectionString))
        {              
            Connection.CreateTable<Character>(CreateFlags.AutoIncPK);
        }
    }
}

【问题讨论】:

  • 我不知道其他任何人,但虽然你的问题很冗长,但它缺乏清晰性。你能用你正在使用的代码重新说明问题吗?
  • 我已经用一个示例类和我的数据库处理类更新了我的问题。每当我创建 Database 类的新实例并且构造函数运行时,CreateTable 方法都会抛出 NotSupportedException,表示它不知道该类。我的问题是,我从 SQLite 需要了解的关于我的课程的代码中遗漏了什么。
  • 您将不得不等待该领域的知识渊博的人,但您似乎并未创建table。数据库中的表必须具有名称和数据结构,即具有类型和大小的数据项。例如创建表注释(note_text,note_number INTEGER);我没有看到任何证据。

标签: c# sqlite


【解决方案1】:

描述您的表的类必须是公开的。 在您的示例中,字符类不是公开的。

您应该像这样更改声明:

[Table("Character")]
public class Character
{
// your class code...
}

【讨论】:

    【解决方案2】:

    我知道回答原来的问题有点晚了,但由于我的 Google-Fu 引导我来到这里,我希望这能帮助遇到同样错误消息的其他人:

    在我将作为公共静态属性添加到具有 [table] 属性的类后,我开始收到此错误消息。给属性添加[Ignore]属性后,我不再收到错误信息了。

    【讨论】:

      猜你喜欢
      • 2021-06-18
      • 2018-12-03
      • 2023-02-24
      • 2017-05-30
      • 1970-01-01
      • 2012-02-21
      • 1970-01-01
      • 2021-03-01
      • 2020-01-21
      相关资源
      最近更新 更多