2

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?

4

2 回答 2

2

很难回答,因为它过于依赖项目的要求。

表示继承层次结构有三种不同的方法:

Table per Hierarchy ( TPH ):通过非规范化 SQL 模式启用多态性,并利用保存类型信息的类型鉴别器列。

每个类型的表(TPT:将“is a”(继承)关系表示为“has a”(外键)关系。

每个具体类的表 ( TPC ):完全从 SQL 模式中丢弃多态性和继承关系。

您应该检查链接并找到最适合您需要的模型。

于 2013-11-04T13:01:33.807 回答
0

使用列表和分类管理器:

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;
}
于 2013-11-04T12:24:25.670 回答