从列表中填充 ICollection,ICollection returns null

Fill ICollection from List, ICollection returns null

我有以下型号

 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>();
    }
 }

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 是 SQL 服务器上的一个大视图,性能低下,我无法在一次查询中查询结果。 一次检索一项时性能良好。

我使用这个查询检索数据

  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);

正如您在评论中看到的那样,当我将 ItemPrices 添加到 SalesPrices 时,它从空列表 Count = 0 变为 NULL 列表。

我正在努力解决这个问题,我怎样才能用列表填充 ICollection?

亲切的问候

杰伦

问题是在这段代码中

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 是匿名对象列表,不能使用 as 将其转换为类型 ItemPrices 的对象列表。因此cast操作prices as ICollection<ItemPrices> returns null.

要解决此问题,您在获取 ItemPrices:

时不应使用投影 (Select(...))
var prices = db.ItemPrices
    .Where(a => a.Id == testId)
    .ToList();

// Now casting to ICollection<ItemPrices> is not needed.
item.SalesPrices = prices;