在ASP.NET webforms中使用EntityDatasource进行过滤

时间:2012-11-02 11:47:36

标签: c# asp.net linq entity-framework

我有两个类(通过实体框架给出),这些类具有多对多的关系:

Corporation which has the member Tags

Tag which has the member name

EntityDataSource给了我想要在给定标记名中过滤但我不知道如何过滤的ObjectQuery。我希望得到所有公司,其标签名为“myname”。我不知道怎么做linq查询

当我查询实体时,我很遗憾没有获得Objectquery。

protected void EntityDataSource1_QueryCreated(object sender, QueryCreatedEventArgs e)
{
    // first try
    var corps = e.Query.Cast<Corporation>(); 
    // of course doesn't work, because oyu can't access a member (name) of a collection (Tags) 
    // i don't know the right linq expression for this
    e.Query = from c in corps where c.Tags.Name.Contains("myname") select c; 

    // second try
    var tags = from t in entities.Tags where t.Name.Contains("myname") select t;
    var filteredcorporations = from c in tags select c.Corporations;
    // does not work because it is not a ObjectQuery<Corporation>
    e.query = filteredcorporations; 
}

我的EntityDataSource:

<asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=eodbEntities" DefaultContainerName="eodbEntities" EnableFlattening="False" EntitySetName="Corporations" OnQueryCreated="EntityDataSource1_QueryCreated">
</asp:EntityDataSource>

2 个答案:

答案 0 :(得分:2)

您可以在标记中执行此操作:

<asp:EntityDataSource ID="EntityDataSource1" runat="server" 
    ConnectionString="name=eodbEntities" 
    DefaultContainerName="eodbEntities" EnableFlattening="False" 
    EntitySetName="Corporations" Select=""
    Where="it.Tags.Name.Contains(@tagname)">
    <WhereParameters>
        <asp:ControlParameter DefaultValue="myname" DbType="String" Name="tagname"/>
    </WhereParameters>
</asp:EntityDataSource>

或者

<asp:EntityDataSource ID="EntityDataSource1" runat="server" 
    ConnectionString="name=eodbEntities" 
    DefaultContainerName="eodbEntities" EnableFlattening="False"    
    EntitySetName="Corporations" Select=""
    Where="it.Tags.Name.Contains(&quote;tagname&quote;)">   
</asp:EntityDataSource>

有关详细信息,请参阅here

<强>更新

你的查询无法在标记中完成:(然后试试这个:

protected void EntityDataSource1_QueryCreated(object sender, QueryCreatedEventArgs e)
{
    var productQuery1 = e.Query.OfType<Corporation>();
    e.Query = productQuery1.Where(c => c.Tags.Any(t => t.Name.Contains("myname")));
}

答案 1 :(得分:0)

首先你可以像在这里一样设置过滤值吗

var name ="myname";

你在下面写下你的查询

var filtervilue= from t in entities.Tags where (name==""? name.Contains(t.Name):true) select t


var filteredcorporations = from c in filtervilue select c.Corporations;        
    e.query = filteredcorporations;

我认为这会对你有帮助.....