假设我有这两个对象:
public class Employee : Person
{
public string Something { get; set; }
}
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
现在我必须处理给定的数据库模式,如下所示:
CREATE TABLE employee (
id INTEGER PRIMARY KEY,
something TEXT
);
CREATE TABLE person (
id INTEGER PRIMARY KEY,
firstname TEXT,
lastname TEXT
);
(两者共享相同的ID,因此可以将它们连接到查询中的单个记录。)
问题:我是否有机会通过SQLite-Net Extensions通过sqlite-net解决这个问题?如果是这样的话:那将如何运作?
答案 0 :(得分:1)
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或等效代码来使映射代码更具可读性和可维护性。