我有一种方法,可以从数据库中提取数据,然后将其分配给模型以在其他地方使用。我从数据库中以不同参数获取地址详细信息,如下所示。连接字符串值时,出现以下错误。
请帮我解决这个问题。
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;
}
}
这是我认为给您带来问题的部分:
表达式树可能不包含非数组 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
,你可以在获取数据之后在本地进行格式化,这会让事情变得不那么脆弱。)