2

我有一个必须具有递归关系的表Employee ,例如。

第 1 行: EmployeeId = 1EmployeeName = AlbertSupervisorId = NULL

第 2 行EmployeeId = 2EmployeeName = LeonardoSupervisorId = 1

即 EmployeeId( 2 ) 是 EmployeeId( 1 )的子代

我在 C# 中有以下代码,其中我使用SQLite-Net 扩展来实现递归关系:

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中:

第一名员工

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);
}

此外,当我添加第二名员工而不指定外键并进行调用时,它可以工作......

4

2 回答 2

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可能是错误的方法。

于 2014-05-26T09:03:11.400 回答
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; }
}

我已经对其进行了测试,并且可以按预期工作。但是,我在 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; }
}

希望能帮助到你。

于 2014-08-01T15:55:06.770 回答