Moo-Juice
Moo-Juice

Reputation: 38800

Retrieving Hierarchal data in Entity Code-First

I have some hierarchal data. The Model class I use looks like this:

public class Category
{
    [Key]
    public int CategoryID { get; set; }

    [Required]
    [StringLength(64)]
    public string Name { get; set; }

    public int? ParentCategoryID { get; set; }
    [ForeignKey("ParentCategoryID")]
    public Category ParentCategory { get; set; }

    [Required]
    public int ListOrder { get; set; }


    // left/right
    public int TreeLeft { get; set; }
    public int TreeRight { get; set; }
}   // eo class Category

I've used the techniques outlined here to store my data, and inserting and retrieving data is not a problem.

What I would like to do, is add a Category collection to this class:

public virtual IEnumerable<Category> {get; set; }

I've used this technique in the past (learned from the Mvc tutorials), to include related tables when getting data. However, when I tried this I received an error with regard to IEnumerable<> being abstract (which is understandable, I guess the framework couldn't figure out what I want to do)...

... and indeed, being new to LINQ, I have no idea what the LINQ would look like that would give me back a collection of Category instances each of which had their children inside them.

If it's not possible I guess I can construct the list manually, use a regular LINQ query to get all the categories at a particular position (and their children) and manually populate it all.

I was wondering if LINQ could do this for me?

Thanks in advance!

Upvotes: 0

Views: 227

Answers (2)

Euphoric
Euphoric

Reputation: 12849

Dont use IEnumerable<Category> but Collection<Category> . If that is your problem..

Upvotes: 0

Magnus
Magnus

Reputation: 46947

If you have a self reference fk than the collection should be generated automatically when you add the table to the dbml file

And will look something like this:

[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Category_Category", Storage="Categories", ThisKey="pkCategoryID", OtherKey="ParentCategoryID")]
public EntitySet<Category> Categories
{
  get
  {
    return this._Categories;
  }
  set
  {
    this._Categories.Assign(value);
  }
}

Upvotes: 1

Related Questions