如何从复杂类型列表中检索数据库中的对象列表?

时间:2017-03-06 12:40:28

标签: c# entity-framework

我们的域模型(和数据模型)包含值类型LoanValueType。这种类型对每笔贷款都是唯一的。即,LoanKey1和LoanKey2这两个部分在每笔贷款中都是唯一的。

    loans.AddRange(
        _context.Loan
            .Include(x => x.Customer)
            .Include(x => x.Customer.Address)
            //...
            .Where(x => x.Status == ExampleStatus.Completed && x.ExampleDateTime > maxday)
            //...
            .Where(loan => loanIds.Any( x =>
                            x.LoanKey1 == loan.LoanValueType.LoanKey1 &&
                            x.LoanKey2 == loan.LoanValueType.LoanKey2))
        );

我们需要的是从列表中的数据库中获取所有贷款,loanIds(List)。它早先以一种方式解决,导致对数据库的逐个调用完全没有效果。

但是,上面对数据库的查询导致"在此上下文中仅支持原始类型或枚举类型。"。我明白为什么,但找不到解决这个问题的方法。

我试着在最后一个where子句之前枚举,但它给了我一个太大的结果集。我只想从数据库中检索列表中的贷款。

修改

贷款价值类型是这样的

public class LoanValueType
{
    public string LoanKey1 { get; private set; }

    public int? LoanKey2 { get; private set; }
}

1 个答案:

答案 0 :(得分:0)

var separator = "_"; // Consider making it more complex/unique
var loanIdsList = new List<string>();

foreach (var loanId in loanIds)
{
    loanIdsList.Add(loanId.LoanKey1 + separator + loanId.LoanKey2);
}

loans.AddRange(
    _context.Loan
        .Include(x => x.Customer)
        .Include(x => x.Customer.Address)
        //...
        .Where(x => x.Status == ExampleStatus.Completed && x.ExampleDateTime > maxday)
        //...
        .Where(loan => loanIdsList.Contains(loan.LoanValueType.LoanKey1 + separator + loan.LoanValueType.LoanKey2))
    );