【发布时间】:2010-04-04 01:32:30
【问题描述】:
能否在实体框架中为实体添加“或”条件?例如:
属性 1 ==(1 或 2 或 3)
输入“1 || 2 || 3”或“1,2,3”或“1 or 2 or 3”的值时收到的消息返回此消息:
condition is not compatible with the type of the member
【问题讨论】:
标签: entity-framework entity-framework-4
能否在实体框架中为实体添加“或”条件?例如:
属性 1 ==(1 或 2 或 3)
输入“1 || 2 || 3”或“1,2,3”或“1 or 2 or 3”的值时收到的消息返回此消息:
condition is not compatible with the type of the member
【问题讨论】:
标签: entity-framework entity-framework-4
你需要做的:
var results = entityCollection.Where(entity => entity.Property1 == 1 || entity.Property1 == 2 || entity.Property1 == 3);
【讨论】:
entity =>吗?
您还应该检查谓词生成器: http://www.albahari.com/nutshell/predicatebuilder.aspx
它有点高级,但如果您必须动态链接条件,这是您最好的选择。
foreach (string keyword in keywords)
{
string temp = keyword;
predicate = predicate.Or (p => p.Description.Contains (temp));
}
【讨论】:
这个没试过,不过你可以试试contains。不确定性能,但代码更小:
int[] vals = new int[] { 1, 2, 3, 4 };
var results = entityCollection.Where(entity => vals.Contains(entity.Property1));
【讨论】:
Contains 仅在尚未发布的 EF 4 中受支持(它与 .Net 4 一起出现在第 12 个)。 MS 的网站上有一个候选版本。