ORM Lite组合密钥解决方法问题

时间:2016-04-28 13:27:34

标签: ormlite-servicestack

我正在实施此处建议的复合键解决方法:

https://github.com/ServiceStack/ServiceStack.OrmLite/#limitations

但我收到了SQL错误"无效的列名称' ID'"尝试使用复合键值进行SELECT时。 SQL事件探查器显示SELECT确实包含一个列' ID'所以我理解SQL错误。我不确定如何在不收到错误的情况下使用变通方法?

DTO:

public class EmploymentHistory {
    [PrimaryKey]                        // Workaround - Composite Key => Unique Key
    public string ID {
        get {
            return
                this.EmployeeID + "|"
                +
                this.DepartmentID + "|"
                +
                this.TitleID + "|"
                +
                this.StartDate.ToString("yyyy-MM-dd");
        }
    }
    public int EmployeeID { get; set; }
    public int DepartmentID { get; set; }
    public int TitleID { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime? EndDate { get; set; }

    [Ignore]
    public Department Department { get; set; }
    [Ignore]
    public Title Title { get; set; }
}

请求DTO:

[Route("/employmenthistory/{EmployeeID}/{DepartmentID}/{TitleID}/{StartDate}", "GET")]
public class SingleEmploymentHistoryRequest : IReturn<Employee> {
    public int EmployeeID { get; set; }
    public int DepartmentID { get; set; }
    public int TitleID { get; set; }
    public DateTime StartDate { get; set; }
}

服务方式:

public object Get(SingleEmploymentHistoryRequest request) {
    EmploymentHistory employmentHistory = Db.Select<EmploymentHistory>()
        .Where(eh =>
            eh.EmployeeID == request.EmployeeID
            &&
            eh.DepartmentID == request.DepartmentID
            &&
            eh.TitleID == request.TitleID
            &&
            eh.StartDate.Date == request.StartDate.Date).FirstOrDefault();

    if (employmentHistory == null)
        throw new WebServiceException("EmploymentHistory not found");

    return employmentHistory;
}

1 个答案:

答案 0 :(得分:1)

您不需要为自定义查询指定虚假的ID主键:

var employmentHistory = Db.Single<EmploymentHistory>(eh =>
    eh.EmployeeID == request.EmployeeID &&
    eh.DepartmentID == request.DepartmentID &&
    eh.TitleID == request.TitleID &&
    eh.StartDate >= startDate.Date && 
    eh.StartDate < startDate.Date.AddDays(1)));