0

假设我有这两个对象:

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 解决这个问题吗?如果是这样:那将如何运作?

4

1 回答 1

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或等效工具来使映射代码更具可读性和可维护性。

于 2015-04-08T11:13:24.697 回答