0

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

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)

如果没有额外的选择来获取地址,一切都很好,除了我们没有得到地址。

我们得到错误:

子查询返回超过 1 个值。当子查询跟随 =、!=、<、<=、>、>= 或子查询用作表达式时,这是不允许的。

有什么建议么 ?

4

1 回答 1

1

您不能将列表返回到SQL. 您可以使用破折号连接数据并存储在这样的列中,-您可以拆分 AddressData并存储在列表中。c#-

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();
        }
    }
}
于 2020-06-17T09:47:53.923 回答