开发者

Can I get a custom sorted EntityCollection by default in EntityFramework?

I would like to call a method in the ObjectContext which returns EntityCollection and have it sorted the way I want by default. For example, Imagine I have the following Category table/class:

  • CategoryID (PK)
  • Name
  • ParentID (FK_Category) foreign key pointing to CategoryID itself.

(This table is the base for a tree structure of Categories and SubCategories)

Now, in my data model, the public partial class Category : EntityObject has a property which returns all Categories that have ParentID==CategoryID, in other words, EntityCollection<Category> SubCategories.

Alright, now i want to show in my page all the Categories and SubCategories by using Repeater:

<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>

Then in code behind, I set the DataSource:

IList<Category> categoryList = new CategoryProvider().GetAll();
rptSubCategories.DataSource = categoryLi开发者_运维百科st;
rptSubCategories.DataBind();

Simply and everything works! Except that, rptSubCategoryCategories doesn't gives sorted Categories by Name. The only way I found to do it, is to change its DataSource from:

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

to:

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

but I wish I could do something else to have a default sorting so i don't need to call the OrderBy. Something like Attributes like we do in DynamicData, following the tutorial at http://www.asp.net/learn/3.5-SP1/video-291.aspx Setting the default sort column of an Entity with DisplayColumnAttribute. Unless somebody tells me it's impossible what I want to do.

Using .NET 4.0 BETA 2

Thank you, I appreciate any post!


As far as I'm aware this is not possible.

You could create an additional property called SortedSubCategories

e.g.

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

I'm curious though why is using the OrderBy such an issue?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜