【问题标题】:How to map subquery in stored procedure in EF Core如何在 EF Core 的存储过程中映射子查询
【发布时间】:2020-10-06 22:27:23
【问题描述】:

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

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 个值。当子查询跟随 =、!=、、>= 或子查询用作表达式时,这是不允许的。

有什么建议吗?

【问题讨论】:

    标签: sql-server entity-framework stored-procedures


    【解决方案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();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-22
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      相关资源
      最近更新 更多