首页 文章

访问外键数据linq

提问于
浏览
0

如果通过sql查询完成,我有一个简单的要求 . 我有表A,它是具有ID的类,名表b是categoryItems,其具有A CategoryId,Name的外键 . 我使用linqdatasource和简单的select语句来显示表A中的数据 .

select * from A (simple)

我现在有一个要求,我想首先“不显示”类别没有与他们相关的任何项目我 . e(从B中选择Count(*),其中CategoryId =“”)> 0

通过修改sql语句非常容易,想知道是否可以通过使用任何开箱即用的linq功能访问外键关系数据并应用验证来完成 .

只是热衷于它!..

万分感谢!

2 回答

  • 0

    你可以试试这个

    var categories = (from c in category select c).Select<Category>(x => x.categoryItems.Count() > 0);
    

    这依赖于你的对象,并且可以很好地完成这个任务 .

    或者,您也可以使用 Where 等 .

    See this link for a good explanation on Linq operators and extenders

  • 2

    你想在 Category.CategoryItems 上使用 Any() 方法

    Any() 返回 true 如果 Count > 0false 如果 Count == 0

    // Select only the Categories which have at least one CategoryItem.
    IEnumerable<Category> categoriesWithItems = Context.Categories.Select(x => x.CategoryItems.Any());
    

    对于 linqdatasource ,您想使用 Selecting event handler . MSDN .

    aspx: -

    <asp:LinqDataSource ID="LinqDataSource1"
                    runat="server"  
                    ContextTypeName="MyDataContext"
                    OnSelecting="LinqDataSource1_Selecting">
    </asp:LinqDataSource>
    

    方法:-

    public void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    { 
        e.Result = categoriesWithItems = Context.Categories.Select(x => x.CategoryItems.Any());    
    }
    

相关问题