[英]Name table in SQLite-net
我正在构建一个 Windows 8 C#/XAML 应用程序,它使用 SQLite 作为存储数据库,并且我正在尝试使用 SQLite.net 语法创建多个表。
根据我到目前为止的研究,一个表是基于 class 创建的。首先,我通过以下方式创建了一个“帐户”class:
public class Account
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string Name { get; set; }
public string Type { get; set;}
}
然后创建一个表并稍后在代码中通过以下方式输入初始数据:
private static readonly string _dbPath =
Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "data.sqlite");
using (var db = new SQLite.SQLiteConnection(_dbPath))
{
db.CreateTable<Account>();
db.RunInTransaction(() =>
db.Insert(new Account()
{
Name = "MyCheckingAccount",
Type = "Checking",
})
);
}
我想创建多个帐户表,但db.CreateTable<Account>()
语法仅创建一个表,并使用db.Insert().
我看不到在哪里输入表本身的名称。
如何创建多个表,即一个名为“BusinessAccounts”的表和另一个基于帐户 class 的“PersonalAccounts”?
有没有办法用 SQLite.net 做到这一点? 或者我是否需要以某种方式显式写出 SQLite 命令?
这个答案似乎已经过时了,在SQLite-net中,您现在可以在类上使用属性来更改表名,例如:
[SQLite.Table("table_customers")]
public class Customer
{
[MaxLength(3)]
public string code { get; set; }
[MaxLength(255)]
public string name { get; set; }
}
因此它将创建/更新该表。
Sqlite-Net使用类名称来创建表以及更新数据。 要执行所需的操作,您需要创建单独的类。 避免重复公共字段的一种方法是使用继承:
public class Account
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string Name { get; set; }
public string Type { get; set;}
}
public class BusinessAccounts : Account { }
public class PersonalAccounts : Account { }
要创建表:
db.CreateTable<BusinessAccounts>();
db.CreateTable<PersonalAccounts>();
要插入数据:
db.Insert(new BusinessAccounts() {...});
db.Insert(new PersonalAccounts() {...});
请注意,上面的代码未经测试。 您将要确保正确创建了表(例如,使用正确的主键和自动增量字段)。
只需添加 SQLite.net,您可以通过实现初始化重载并设置 SQLite.TableAttribute 来更改 class 的属性,如下所示:
[Table("Account")]
public class Account
{
[PrimaryKey]
[AutoIncrement]
public int ID { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public Account(string name = null)
{
if (!string.IsNullOrEmpty(name))
{
TableAttribute attrname = TypeDescriptor.GetAttributes(this)(0);
attrname.Name = name;
}
}
}
该名称默认为帐户,但如果您使用字符串初始化 class,它会设置该属性,因此您可以使用该名称创建一个表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.