【问题标题】:Can I get a custom sorted EntityCollection by default in EntityFramework?我可以在 Entity Framework 中默认获取自定义排序 EntityCollection 吗?
【发布时间】:2010-01-15 20:26:31
【问题描述】:

我想在ObjectContext 中调用一个返回EntityCollection 的方法,并让它按照我想要的默认方式排序。例如,假设我有以下Category 表/类:

  • 类别 ID (PK)
  • 姓名
  • ParentID (FK_Category) 外键 指向 CategoryID 本身。

(此表是类别和子类别树结构的基础)

现在,在我的数据模型中,public partial class Category : EntityObject 有一个属性,它返回所有具有 ParentID==CategoryID 的类别,换句话说,EntityCollection<Category> SubCategories

好的,现在我想通过使用中继器在我的页面中显示所有类别和子类别:

<asp:Repeater ID="rptSubCategories" runat="server">
<ItemTemplate>
    <%# Eval("CategoryID") %> - <%# Eval("Name") %>

    <asp:Repeater ID="rptSubCategoryCategories" runat="server" DataSource='<%#Eval("SubCategories")) %>'>
    <ItemTemplate>
        <%# Eval("CategoryID") %> - <%# Eval("Name") %>
    </ItemTemplate>
    </asp:Repeater>

</ItemTemplate>
</asp:Repeater>

然后在后面的代码中,我设置了数据源:

IList<Category> categoryList = new CategoryProvider().GetAll();
rptSubCategories.DataSource = categoryList;
rptSubCategories.DataBind();

简单,一切正常!除此之外,rptSubCategoryCategories 不提供按名称排序的类别。我发现这样做的唯一方法是将其 DataSource 更改为:

DataSource='<%# Eval("SubCategories")) %>'

到:

DataSource='<%# ((EntityCollection<Category>)Eval("SubCategories")).OrderBy(p => p.Name) %>'

但我希望我可以做一些其他事情来进行默认排序,这样我就不需要调用 OrderBy。按照http://www.asp.net/learn/3.5-SP1/video-291.aspx 的教程,类似我们在 DynamicData 中所做的 Attributes 使用 DisplayColumnAttribute 设置实体的默认排序列。除非有人告诉我,我想做的事情是不可能的。

使用 .NET 4.0 BETA 2

谢谢你,感谢任何帖子!

【问题讨论】:

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


    【解决方案1】:

    据我所知这是不可能的。

    您可以创建一个名为 SortedSubCategories 的附加属性

    例如

          public EntityCollection<Category> SortedSubCategories
            {
                get
                {
                    return SubCategories.OrderBy(p => p.Name);
                }
            }
    

    我很好奇为什么使用 OrderBy 这样的问题?

    【讨论】:

    • 嘿,威比特!我期待这个答案,只是想确保这是不可能的。我仍然希望你能证明我们错了。原因只是为了让代码看起来更漂亮,仅此而已。你在这件事上帮助我,因为目前的方法看起来很难看。所以非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    相关资源
    最近更新 更多