karavanjo
karavanjo

Reputation: 1751

Entity Framework: Model for Categories/Products relation

I have following model of data for Entity Framework.

I have abstract Product. Every Product relates with one Category of products. For example:

public abstract class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Category Category { get; set; }
}

And there are concrete products:

public class ConcreteProduct1 : Product
{
    // some specific member
}

public class ConcreteProduct2 : Product
{
    // some specific member
}

//etc.

I have hierarchical Categories, for example:

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Category Parent { get; set; }
    public ICollection<Category> Children { get; set; }
    public ICollection<Product> Products { get; set; }
}

Every Category has ICollection<Product> Products.

Problem: Category should be related with only products some concrete product type. I.e. I need be able get Concrete Products into Category, for example:

public Category<ConcreteProduct1> GetCategory<ConcreteProduct1> ()
{
    // should return Category that contain ICollection<ConcreteProduct1>
}

How I can describe this restriction in my Entity Framework model? Or may be there are some best practice for building these relations?

Upvotes: 2

Views: 2404

Answers (2)

jlvaquero
jlvaquero

Reputation: 8785

It is hard to answer because it depends too much on the requisites of your project.

There are three different approaches to representing an inheritance hierarchy:

Table per Hierarchy (TPH): Enable polymorphism by denormalizing the SQL schema, and utilize a type discriminator column that holds type information.

Table per Type (TPT): Represent "is a" (inheritance) relationships as "has a" (foreign key) relationships.

Table per Concrete class (TPC): Discard polymorphism and inheritance relationships completely from the SQL schema.

You should check the links and find what is the best suitable model for what you need.

Upvotes: 2

111WARLOCK111
111WARLOCK111

Reputation: 867

Use lists and a categorymanager:

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Category Parent { get; set; }
    public ICollection<Category> Children { get; set; }
    public List<Product> Products = new List<Product>();
}

public static class CategoryManager
{
    public List<Category> Categories = new List<Category>();
}

public Product test = new Product
{
    Id = 1
};

public Category add = new Category
{
    Id = 1
};

public void Init()
{
    add.Products.Add(test);
    CategoryManager.Categories.Add(add);
}

public Product GetByID(Category cat, string val)
{
   return cat.Where(x => x.Id == val).ToArray()[0];
}

public Category GetCat(Product pro)
{
    foreach (var cat in CategoryManager.Categories)
    {
       if (cat == pro) return cat;
    }
    return null;
}

Upvotes: 0

Related Questions