尝试连接字符串时,出现表达式树不能包含引用结构值或受限类型错误

问题描述 投票:0回答:1

我有一种方法,可以从数据库中提取数据,然后将其分配给模型以在其他地方使用。我从数据库中以不同参数获取地址详细信息,如下所示。连接字符串值时,出现以下错误。

请帮我解决这个问题。

Expression tree cannot contain value of ref struct or restricted type.

An expression tree may not contain an expanded form of non-array params collection parameter.

以下代码

 public async Task<InvoiceLocationDTO> GetLocationDetails(int locId)
 {
     try
     {
         InvoiceLocationDTO? locationDetails = await (
             from loc in context.Location.Where(loc => loc.Id == locId)
             .Include(x => x.LocationAddress)             

             select new InvoiceLocationDTO
             {
                 ///Getting error in below line
                 BillToAddress = string.Format(" {0}, {1}, {2}, {3}, {4}",
                                 loc.LocationAddress.Address, loc.LocationAddress.AddressExtraLine, loc.LocationAddress.City, loc.LocationAddress.State.Name, loc.LocationAddress.Zip)
                                 .Replace(" ,", string.Empty).TrimEnd(','),
             }
         ).FirstOrDefaultAsync();
         return locationDetails;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
c# .net entity-framework-core blazor
1个回答
0
投票

这是我认为给您带来问题的部分:

表达式树可能不包含非数组 params 集合参数的扩展形式。

...因为这正是您对

string.Format
的参数所做的事情。不过,您可以自己创建数组:

BillToAddress = string.Format(" {0}, {1}, {2}, {3}, {4}",
    new object[]
    {
        loc.LocationAddress.Address, 
        loc.LocationAddress.AddressExtraLine,
        loc.LocationAddress.City, 
        loc.LocationAddress.State.Name,
        loc.LocationAddress.Zip)
    }).Replace(" ,", string.Empty).TrimEnd(','),

(也就是说,我怀疑如果你只是获取

loc.LocationAddress
,你可以在获取数据之后在本地进行格式化,这会让事情变得不那么脆弱。)

© www.soinside.com 2019 - 2024. All rights reserved.