Match 2 property of any object in local list using Linq

徘徊边缘 提交于 2020-01-24 15:09:33

问题


    public class OrderItem
    {
        public int OrderID { get; set; }
        public int ProductionID { get; set; }
    }

    public class InventoryItem
    {
        public int InventoryItemID{ get; set; }
        public int OrderID { get; set; }
        public int ProductionID { get; set; }
        public bool Created { get; set; }
        public bool Deleted { get; set; }
    }

Using these example objects,

I have a local list of orderItems and want to query inventory items where OrderID and ProductionID matches on both properties any of my list of Order Items

I tried linq query below but I am getting an error

Query I am trying:

    var results = await db.InventoryItems.Where(d =>
                  listOfOrderItems.Any(o => o.OrderID == d.OrderID && !d.DeleteFlag && d.ProductionId == o.ProductionItemId))
                  .Select(t => t.InventoryItemID).ToListAsync();

Exception thrown: 'System.NotSupportedException' in EntityFramework.SqlServer.dll

EDIT i am being referred to this question:Using Linq to Sql asynchronously with new async/await

But my question is not about async await, it is about the matching 2 properties using the .any on my list


回答1:


Try this:

var localIdPairs = listOfOrderItems.Select(x => x.OrderId + "-" + x.ProductionItemId).ToList();

var results = await db.InventoryItems
          .Where(d => !d.DeleteFlag && 
                      localIdPairs.Contains(d.OrderId + "-" + d.ProductionItemId))
          .Select(t => t.InventoryItemID).ToListAsync();



回答2:


Looking further into the error I found this error:

Only primitive types or enumeration types are supported in this context.

My collection listOfOrderItems was of type List, changing it to IEnumerable fixed my problem



来源:https://stackoverflow.com/questions/59548495/match-2-property-of-any-object-in-local-list-using-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!