【问题标题】:Entity Framework: Model for Categories/Products relation实体框架:类别/产品关系模型
【发布时间】:2015-12-23 21:37:30
【问题描述】:

我有以下实体框架的数据模型。

我有抽象产品。每个产品都与一个产品类别相关。例如:

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

还有具体的产品:

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

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

//etc.

我有分层类别,例如:

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

每个类别都有ICollection&lt;Product&gt; Products

问题:类别应该只与某些具体产品类型的产品相关。 IE。我需要能够将 Concrete Products 放入类别中,例如:

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

如何在我的实体框架模型中描述此限制?或者可能有一些建立这些关系的最佳实践?

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    这很难回答,因为它过多地取决于您项目的要求。

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

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

    Table per Type (TPT):将“is a”(继承)关系表示为“has a”(外键)关系。

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

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

    【讨论】:

      【解决方案2】:

      使用列表和分类管理器:

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

      【讨论】:

      • 谢谢,但很遗憾,我无法理解您的回答 :) 我的问题与 Entity Framewrok 模型有关,即它与 ORM 有关 - 如何将我的域模型表示到数据库中,由Entity Framework Code First 的 C# 代码。我的问题 - 我不需要按类别获取父产品,我需要按类别获取具体产品。我会澄清我的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      • 2018-03-25
      • 2019-09-04
      • 1970-01-01
      • 2011-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多