如何使用实体类创建多个表
public class Info
{
public string firstName { get; set; }
public string lastName { get; set; }
public string imageUrl { get; set; }
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public DetailInfo objDetailInfo{ get; set; }
}
public class DetailInfo
{
public string phoneno { get; set; }
public string address { get; set; }
}
我正在使用以下代码
public void createtable()
{
SQLite.SQLiteConnection db= new SQLite.SQLiteConnection(dbPath);
db.CreateTable<Info>();
var data = new Info() { Id = "1", firstName = "Rehan", imageUrl = "safsdfsdf", lastName = "Parvez", objsty = new objDetailInfo{ address = "Nagpur", phoneno = "902136" } };
db.Insert(data);
}
执行db.CreateTable<Info>()
时,它给我一个错误
答案 0 :(得分:1)
我自己回答我的问题,因为我认为这会对我的其他朋友有所帮助 使用忽略关键字
public class Info
{
public string firstName { get; set; }
public string lastName { get; set; }
public string imageUrl { get; set; }
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[Ignore]
public DetailInfo objDetailInfo{ get; set; }
}
public class DetailInfo
{
public string phoneno { get; set; }
public string address { get; set; }
}
public void createtable()
{
SQLite.SQLiteConnection db= new SQLite.SQLiteConnection(dbPath);
db.CreateTable<Info>();
db.CreateTable<DetailInfo>();
}
答案 1 :(得分:1)
Here是另一种方式,如sqlite-net,
所述综述,
public class Stock
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(8)]
public string Symbol { get; set; }
}
public class Valuation
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[Indexed]
public int StockId { get; set; }
public DateTime Time { get; set; }
public decimal Price { get; set; }
}
通过这些,您可以通过调用CreateTable:
自动在数据库中生成表var db = new SQLiteConnection("stocks.db");
db.CreateTable<Stock>();
db.CreateTable<Valuation>();
您可以使用Insert在数据库中插入行。如果表包含自动递增的主键,则插入后将为您提供该键的值:
public static void AddStock(SQLiteConnection db, string symbol) {
var s = db.Insert(new Stock() {
Symbol = symbol
});
Console.WriteLine("{0} == {1}", s.Symbol, s.Id);
}
您可以使用SQLiteConnection的Query方法查询数据库:
public static IEnumerable<Valuation> QueryValuations (SQLiteConnection db, Stock stock)
{
return db.Query<Valuation> ("select * from Valuation where StockId = ?", stock.Id);
}
此查询也可以使用Linq语法编写,以便您键入安全性,以便您的重构是安全的:
public static IEnumerable<Valuation> QueryValuations (SQLiteConnection db, Stock stock)
{
return db.Table<Valuation> ().Where(v => v.StockId == stock.Id);
}
Query方法的泛型参数指定要为每行创建的对象类型。它可以是您的一个表类,也可以是其公共属性与查询返回的列匹配的任何其他类。 Table方法要求存在一个与返回类型同名的表。
public class Val {
public decimal Money { get; set; }
public DateTime Date { get; set; }
}
public static IEnumerable<Val> QueryVals (SQLiteConnection db, Stock stock)
{
return db.Query<Val> ("select \"Price\" as \"Money\", \"Time\" as \"Date\" from Valuation where StockId = ?", stock.Id);
}