C# 无法创建常量值 - 只有原始类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10862491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unable to create a constant value - only primitive types
提问by Anton Putov
Two simple queries - the exception occurs in :
两个简单的查询 - 异常发生在:
matchings.Any(u => product.ProductId == u.ProductId)
What is wrong? If I write trueinstead it all is good.
怎么了?如果我改写true,一切都很好。
var matchings = (from match in db.matchings
where match.StoreId == StoreId
select match).ToList();
var names = (from product in db.Products
where matchings.Any(u => product.ProductId == u.ProductId)
select product).ToList();
采纳答案by Rapha?l Althaus
First way :
第一种方式:
Remove ToList()in the first query.
ToList()在第一个查询中删除。
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).
因为我认为您在 linq2entities 中,并且您在查询中使用了一个匹配列表,这是不可能的(您的主题标题往往让我相信这是您的问题)。
回答by agent-j
This looks like a place to use join
这看起来像一个使用 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;
回答by Ben Pretorius
You can try the following. It has worked for me as my ProductId os of type nullable.
您可以尝试以下操作。它对我有用,因为我的 ProductId os 类型为可空。
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.
这在我的情况下有效,因为目标 id 是可空类型,因为它指向 1:0 -> * 关系。
回答by RMalke
I was facing the same issue when writing the following query using collection and EF tables:
使用集合和 EF 表编写以下查询时,我遇到了同样的问题:
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 orderin 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();

