[英]Fill ICollection from List, ICollection returns null
I've the following model我有以下 model
public class Items
{
[Key]
public Guid Id { get; set; }
public string ItemCode { get; set; }
public virtual ICollection<ItemPrices> SalesPrices { get; set; }
public App4Sales_Items()
{
SalesPrices = new HashSet<ItemPrices>();
}
}
And和
public class ItemPrices
{
[Key, Column(Order = 0), ForeignKey("Items")]
public Guid Id { get; set; }
public virtual App4Sales_Items Items { get; set; }
[Key, Column(Order=1)]
public Guid PriceList { get; set; }
public decimal PriceExcl { get; set; }
public decimal PriceIncl { get; set; }
public decimal VatPercentage { get; set; }
}
ItemPrice is a large View on SQL Server with low performance, I cannot ask the results in one query. ItemPrice 是 SQL 服务器上的一个大视图,性能低下,我无法一次查询结果。 The performance is good when retrieved one item at a time.一次检索一项时性能良好。
I retrieve the data using this query我使用此查询检索数据
var test = db.Items
.OrderBy(i => i.ItemCode)
.Skip(opts.Skip.Value)
.Take(100)
.Select(i => new
{
i.Id,
i.ItemCode,
}).ToList();
List<Items> result = new List<Items>();
for (int i = 0; i < test.Count; i++)
{
Items item = new Items()
{
Id =test[i].Id,
ItemCode = test[i].ItemCode,
};
Guid testId = test[i].Id;
var prices = db.ItemPrices
.Where(a => a.Id == testId)
.Select(a => new
{
a.Id,
a.PriceList,
a.PriceExcl,
a.PriceIncl,
a.VatPercentage
}).ToList();
// ItemPrices is for example a list of 15 items
// Here is SalesPrices Count = 0
item.SalesPrices = prices as ICollection<ItemPrices>;
//Here is Salesprices =null
result.Add(item);
As you can see in the comments when I add the ItemPrices to SalesPrices it turns from an empty list, Count = 0, to a List that is NULL.正如您在评论中看到的,当我将 ItemPrices 添加到 SalesPrices 时,它从一个空列表 Count = 0 变为一个列表 NULL。
I'm struggling to figure this out, how can I fill the ICollection with the List?我正在努力解决这个问题,如何用列表填充 ICollection?
Kind regards亲切的问候
Jeroen杰伦
The problem is that in this piece of code问题是在这段代码中
var prices = db.ItemPrices
.Where(a => a.Id == testId)
// Here anonymous objects are created.
// Therefore "prices" is a list of anonymous objects.
.Select(a => new
{
a.Id,
a.PriceList,
a.PriceExcl,
a.PriceIncl,
a.VatPercentage
}).ToList();
item.SalesPrices = prices as ICollection<ItemPrices>;
prices
is a list of anonymous objects, and it cannot be casted using as
into list of objects of type ItemPrices
. prices
是匿名对象的列表,不能使用as
转换为ItemPrices
类型的对象列表。 Therefore cast operation prices as ICollection<ItemPrices>
returns null.因此,将操作prices as ICollection<ItemPrices>
返回 null。
To fix the problem you should not use projection ( Select(...)
) when getting ItemPrices
:要解决问题,您在获取ItemPrices
时不应使用投影( Select(...)
):
var prices = db.ItemPrices
.Where(a => a.Id == testId)
.ToList();
// Now casting to ICollection<ItemPrices> is not needed.
item.SalesPrices = prices;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.