我有一个表Employee,它必须具有递归关系,例如。
第 1 行:EmployeeId = 1,EmployeeName = Albert,< em>SupervisorId = NULL;
第 2 行:EmployeeId = 2,EmployeeName = Leonardo,< em>SupervisorId = 1;
即EmployeeId(2) 是 EmployeeId(1) 的 child
我在 C# 中有以下代码,我在其中使用 SQLite-Net Extentions实现递归关系:
public class Employee
{
public Employee()
{
Subordinates = new List<Employee>();
}
[PrimaryKey]
[MaxLength(36)]
public string EmployeeGuid { get; set; }
public string EmployeeName { get; set; }
[OneToMany("SupervisorGuid")]
public List<Employee> Subordinates { get; set; }
[ManyToOne("EmployeeGuid")]
public Employee Supervisor { get; set; }
[ForeignKey(typeof(Employee))]
[MaxLength(36)]
public string SupervisorGuid { get; set; }
}
接下来我测试代码 - 我创建了两个员工并将他们添加到表Employee:
第 1 员工
Employee employee1 = new Employee
{
EmployeeGuid = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
EmployeeName = "Albert"
};
Insert(employee1);
第 2 员工
Employee employee2 = new Employee
{
EmployeeGuid = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
EmployeeName = "Leonardo",
SupervisorGuid = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
};
Insert(employee2);
但是当我打电话的时候
GetByGuid(string guid)
guid 是第一个员工,我收到以下错误:
Additional information: Object of type 'Project.Models.Employee' cannot be converted to type 'System.Collections.Generic.List`1
SQLite-Net 是否支持递归关系?有什么建议吗?
更新
GetByGuid() 的代码:
public T GetByGuid(string guid)
{
return Database.GetWithChildren<T>(guid);
}
此外,当我添加 2nd 员工而不指定外键并进行调用时,它会工作...
最佳答案
在递归关系中,您必须手动指定反向关系,如下所示:
public class Employee
{
[PrimaryKey]
[MaxLength(36)]
public string EmployeeGuid { get; set; }
public string EmployeeName { get; set; }
[OneToMany(inverseProperty: "Supervisor")]
public List<Employee> Subordinates { get; set; }
[ManyToOne(inverseProperty: "Subordinates")]
public Employee Supervisor { get; set; }
[ForeignKey(typeof(Employee))]
[MaxLength(36)]
public string SupervisorGuid { get; set; }
}
我已经对其进行了测试,它按预期工作。但是,我创建了 a new issue in bitbucket因为我认为这种行为可以改进,所以这种情况在不久的将来会奏效:
public class Employee
{
[PrimaryKey]
[MaxLength(36)]
public string EmployeeGuid { get; set; }
public string EmployeeName { get; set; }
[OneToMany]
public List<Employee> Subordinates { get; set; }
[ManyToOne]
public Employee Supervisor { get; set; }
[ForeignKey(typeof(Employee))]
[MaxLength(36)]
public string SupervisorGuid { get; set; }
}
希望对您有所帮助。
关于c# - 如何使用 SQLite-Net Extensions 实现递归关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23866079/