SQLite.Net 映射将对象层次结构扁平化为单个表,因此如果让 SQLite.Net 创建表,您将获得这些完全不相关的表:
CREATE TABLE employee (
id INTEGER PRIMARY KEY,
firstname TEXT,
lastname TEXT,
something TEXT
);
CREATE TABLE person (
id INTEGER PRIMARY KEY,
firstname TEXT,
lastname TEXT
);
对后者的更改不会影响前者,反之亦然。您将能够使用自定义查询进行读取和写入,但您将无法将 SQLite.Net 的任何实用方法与该模式和那些类一起使用。
根据您的需要,您可以添加将在数据库操作中使用的中间类,然后将它们映射到模型类。像这样的东西:
[Table("employee")]
public class DBEmployee
{
[PrimaryKey]
public int Id { get; set; }
public string Something { get; set; }
}
[Table("person")]
public class DBPerson
{
[AutoIncrement, PrimaryKey]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class DBService {
static SQLiteConnection _connection;
public void SaveEmployee(Employee employee) {
var dbPerson = new DBPerson {
FirstName = employee.FirstName,
LastName = employee.LastName
};
_connection.Insert(dbPerson);
var dbEmployee = new DBEmployee {
Id = dbPerson.Id,
Something = employee.Something
};
_connection.Insert(dbEmployee);
}
public Employee GetEmployee(int employeeId) {
var dbEmployee = _connection.Get<DBEmployee>(employeeId);
var dbPerson = _connection.Get<DBPerson>(employeeId);
return new Employee {
Id = employeeId,
Something = dbEmployee.Something,
FirstName = dbPerson.FirstName,
LastName = dbPerson.LastName
};
}
}
您可以使用AutoMapper或等效工具来使映射代码更具可读性和可维护性。