【问题标题】:EntityDataSource WHERE IN实体数据源在哪里
【发布时间】:2017-02-09 09:33:27
【问题描述】:

我有一个asp:EntityDataSource

<asp:EntityDataSource ID="EntityDataSource1" runat="server" 
    ConnectionString="name=MyEntities"  DefaultContainerName="MyEntities" 
    EntitySetName="Student" Where="it.Age = 12 or it.Age = 13"> 
</asp:EntityDataSource>

现在我需要显示更多年龄。有没有办法写得更短?

我的尝试:

<asp:EntityDataSource ID="EntityDataSource1" runat="server" 
    ConnectionString="name=MyEntities"  DefaultContainerName="MyEntities" 
    EntitySetName="Student" Where="it.Age IN (11,12,13,14)"> 
</asp:EntityDataSource>

但这会引发错误

set 表达式的右参数必须是 CollectionType。

【问题讨论】:

  • 怎么样:Where="it.Age &gt;= 11 and it.Age &lt;= 14"
  • @NawedNabiZada 好主意,但在我的实际应用中也存在差距
  • 我对asp.net不太熟悉,但数组不应该在{ }而不是( )吗?
  • @NawedNabiZada 是的,但这不是C#,也不是SQL 语法
  • @TetsuyaYamamoto 请添加这个作为答案(因为它是正确的),所以我们看到这个问题已经被处理了。

标签: c# asp.net entity-framework


【解决方案1】:

EntityDataSourceWhere 属性上使用IN 子句的正确方法是将大括号块包围所有值,如数组声明:

<asp:EntityDataSource ID="EntityDataSource1" runat="server" 
    ConnectionString="name=MyEntities"  DefaultContainerName="MyEntities" 
    EntitySetName="Student" Where="it.Age IN {11,12,13,14}"> 
</asp:EntityDataSource>

使用花括号的原因可能取决于ObjectQuery,它在给定的上下文中接收针对模型的类型化查询,它可能接受值数组。换句话说,IN 子句在 LINQ 格式上是等价的:

int[] ages = new int[] {11, 12, 13, 14};
var query = MyEntities.Student.Where(it => it.Age.Contains(ages));

生成的 SQL 命令会变成:

SELECT * FROM [MyEntities].[Student] WHERE Age IN (11,12,13,14)

其他可能的原因是 ASPX 页面标记中的服务器控制语法遵循关于 attribute value templates 的 XSLT 约定,它将大括号块解释为字符串值表达式,而括号则被视为方法参数/表达式附件(请参阅 XSL transformation details)。

类似问题:

EntityDataSource Where Clause in VB.NET

补充参考:

Creating IN Queries

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-31
    • 2023-03-09
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多