使用相同的键连接两个记录

Joining two records with the same key

假设我有这两个对象:

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 扩展的 sqlite-net 解决这个问题吗?如果是这样:那将如何工作?

SQLite.Net 映射将对象层次结构扁平化为单个 table,因此如果您让 SQLite.Net 创建 table,您将获得这些完全不相关的 tables:

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 或等价物来提高映射代码的可读性和可维护性。