c# - 使用 IN 子句的手动(动态)LINQ 子查询

标签 c# entity-framework

我想通过LINQ写手工SQL查询DB,我的linq方法是:

var q = db.TableView.Where(sqlAfterWhere);
returnValue = q.Count();

如果传递给变量“sqlAfterWhere”的值是:(此变量为String类型),则此方法查询良好

it.Name = 'xyz'

但是如果我想使用 IN 子句,使用子查询怎么办。 (我需要在上面查询中的每个列名之前使用“它”才能工作),我不能在子查询列之前使用“它”作为一个单独的查询,所以如果我不使用任何东西我该怎么办,并直接使用列名会给出错误提示 <ColumnName> could not be resolved其中 <ColumnName>是我的列名称,开头没有“它”。

所以查询不起作用是:(这是传递给上面变量的字符串):

it.Name IN (SELECT Name FROM TableName WHERE Address LIKE '%SomeAddress%')

出现的错误是:

Name could not be resolved
Address could not be resolved

准确的错误是:

"'Name' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly., near simple identifier, line 6, column 25."

“Address as well”同样的错误

如果我使用“它”。在这些列之前,它会给出错误:

"The element type 'Edm.Int32' and the CollectionType 'Transient.collection[Transient.rowtype(GroupID,Edm.Int32(Nullable=True,DefaultValue=))]' are not compatible. The IN expression only supports entity, primitive, and reference types. , near WHERE predicate, line 6, column 14."

最佳答案

假设 TableName 也在您的 EF 上下文中并返回与 TableView 相同的类型,您应该能够执行类似的操作

var addresses = db.TableName.Where(x => x.Address.Contains("SomeAddress"));
var q = db.TableView.Intersects(address);
returnValue = q.Count();

关于c# - 使用 IN 子句的手动(动态)LINQ 子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2646603/

相关文章:

c# - 红隼无法启动

entity-framework - Entity Framework ObjectContext 是否正确实现了工作单元模式?

entity-framework - CI 构建服务器上的 EF 迁移

c# - Entity Framework : How can I use more then one context and stay synchronized?

c# - 多线程集差的有效方法

c# - catch 没有捕获到多线程错误

entity-framework - Entity Framework 多对多映射上的软删除

entity-framework - 选择单个实体的一部分而不检索整个实体

c# - NinjectMVC3 的 WebActivator.PreApplicationStartMethod 程序集属性在我的 View 源代码编辑器中导致警告

c# - Task.WaitAll 没有等待 - 解释