我有一个表员工,必须有一个递归关系,例如。
第1行: EmployeeId = 1 ,员工姓名 = Albert ,< em> SupervisorId = NULL ;
第2行: EmployeeId = 2 , EmployeeName = Leonardo ,< em> SupervisorId = 1 ;
即。 EmployeeId( 2 )是EmployeeId的子项( 1 )
我在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; }
}
接下来我测试代码 - 我创建了两个 Employees并将它们添加到表 Employee :
第一个员工
Employee employee1 = new Employee
{
EmployeeGuid = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
EmployeeName = "Albert"
};
Insert(employee1);
第二员工
Employee employee2 = new Employee
{
EmployeeGuid = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
EmployeeName = "Leonardo",
SupervisorGuid = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
};
Insert(employee2);
但是当我打电话时
GetByGuid(string guid)
guid 是第一名员工,我收到以下错误:
其他信息:'Project.Models.Employee'类型的对象无法转换为'System.Collections.Generic.List`1
类型
SQLite-Net是否支持递归关系?有什么建议吗?
更新
GetByGuid代码():
public T GetByGuid(string guid)
{
return Database.GetWithChildren<T>(guid);
}
当我在没有指定外键的情况下添加第二员工并进行调用时,它也有效......
答案 0 :(得分:2)
似乎GetWithChildren
不会返回T
,而是List<T>
,所以您需要执行以下操作:
public IEnumerable<T> GetByGuid(string guid)
{
return Database.GetWithChildren<T>(guid);
}
或者如果您只想要带有提供的Guid
的项目:
public T GetByGuid(string guid)
{
return Database.GetWithChildren<T>(guid)
.FirstOrDefault(i => i.EmployeeGuid == guid);
}
但是GetWithChildren
可能是错误的方法。
答案 1 :(得分:2)
在递归关系中,您必须手动指定反向关系,如下所示:
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; }
}
希望它有所帮助。