如何在 EF Core 的存储过程中映射子查询

How to map subquery in stored procedure in EF Core

我们有以下模型(为简洁起见缩短)

public class Patient 
{
    public int Id {get; set;
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public ICollection<Address> Addresses { get; set; } = new List<Address>();
}

public class Address 
{
    public int PatientId {get; set;
    public string Street { get; set; }
    public string Number { get; set; }
    public string Zip { get; set; }
    public string City { get; set; }
}

我们喜欢使用 EF 将存储过程的结果(患者列表及其地址)映射到他们。

select  
    p.* ,
    (select a.street from Addresses as a where a.PatientId = p.id) as addresses
from 
    Patients as p
where 
    ... (a set of clauses and joins to limit the list to the desired patients)

没有额外的 select 来获取地址,一切正常,好吧,除了我们没有获取地址。

我们收到错误:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

有什么建议吗?

您不能 return 将列表放入 SQL 中的列中。您可以使用破折号 - 连接数据并存储在这样的列中,您可以 Split AddressData in c# by - 和存储在列表中。

select  
    p.* ,
    AddressData = COALESCE(STUFF
    (
            (
                select ' - ' + a.street from Addresses as a where a.PatientId = p.id
                   FOR XML PATH('')
            ), 1,2, N''
    ), N'')
from 
    Patients as p
where 
    ... (a set of clauses and joins to limit the list to the desired patients)
public class Patient 
{
    public int Id {get; set;
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string AddressData { get; set; }
    public ICollection<Address> Addresses 
    {
        get 
        {
            return AddressData.Split('-').ToList().Select(a => new Address 
              {
                   Street = a
              }).ToList();
        }
    }
}