我已经创建了表格,并在其中添加了几行。有没有办法从表中解析我自己的对象?
class Human
{
string name;
int age;
public Human(string name, int age)
{
this.name = name;
this.age = age;
}
}
-- create table
string sql = "create table human (name varchar(20), age int)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
-- insert sample data
string sql = "insert into human (name, age) values ('John', 20)";
command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
-- get the data back from that table
string sql = "select * from human";
command = new SQLiteCommand(sql, m_dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
现在如何从我的读者解析Human
实例?
答案 0 :(得分:2)
是的,有办法。我建议使用 Entity Framework ,这实际上允许您将代码中的类型绑定到数据库中的表。
对于SQLite,这里有几个链接可以帮助您入门:
http://www.bricelam.net/2012/10/entity-framework-on-sqlite.html
http://erikej.blogspot.co.uk/2014/11/using-sqlite-with-entity-framework-6.html
答案 1 :(得分:2)
是的,你可以
它非常简单。 试试这个:
//Create Collection of Human to store the values
List<Human> Humans = new List<Human>();
while (reader.Read())
{
//Create Human Object from Sql Reader
Human h=new Human(reader.getString(0),reader.getInt(1));
//Add the object to collection
Humans.add(h);
}
人类将获得所有人类对象作为行。