Unable to create a constant value - only primitive types

前端 未结 4 1848
北荒
北荒 2020-11-30 08:25

Two simple queries - the exception occurs in :

matchings.Any(u => product.ProductId == u.ProductId)

What is wrong? If I write true

相关标签:
4条回答
  • 2020-11-30 09:02

    You can try the following. It has worked for me as my ProductId os of type nullable.

    IQueryable<matchings> data = db.matchings.Any(u => product.ProductId.Value == u.ProductId);
    

    or this

    IQueryable<matchings> data = db.matchings.Any(u => product.ProductId.Value.Equals(u.ProductId));
    

    This worked in my case as the target id is a nullable type as it points to a 1:0 -> * relationship.

    0 讨论(0)
  • 2020-11-30 09:08

    I was facing the same issue when writing the following query using collection and EF tables:

    var result = (from listItem in list
                  join dbRecord in Context.MY_TABLE
                      on listItem.MyClass.ID equals dbRecord.ID
                  select new { dbRecord, listItem.SomeEnum }).ToList();
    

    I could solve it by changing the source order in in:

    var result = (from dbRecord in Context.MY_TABLE
                  join listItem in list
                      on dbRecord.ID equals listItem.MyClass.ID
                  select new { dbRecord, listItem.SomeEnum }).ToList();
    
    0 讨论(0)
  • 2020-11-30 09:18

    First way :

    Remove ToList() in the first query.

    Or

    //instead of retrieving mathings List, retrieve only the productIds you need (which are a List of Primitive types)
    var productIdList = db.matchings
    .Where(m => m.StoreId == StoreId)
    .Select(x => x.ProductId)
    .ToList();
    
    var products = db.Products
    .Where(p => productIdList
               .Contains(p.ProductId))
    .ToList();
    

    Or

    //other way
    var produts = db.Products
                 .Where(p => db.matchings
                            .Any(m => m.StoreId == StoreId && 
                                 m.ProductId == p.ProductId)
                        )
                 .ToList();
    

    Because I think you're in linq2entities, and you're using a List of Matchings in a query which is not possible (the title of your topic tend to make me believe that's your problem).

    0 讨论(0)
  • 2020-11-30 09:25

    This looks like a place to use join

     var query =
        from product in db.Products
        join matching in db.Matchings
        on product.ProductId equals matching.ProductId into matchGroup
        where matchGroup.Count() > 0 and matching.StoreId == StoreId
        select product;
    
    0 讨论(0)
提交回复
热议问题