如何在SQL Server上映射属于同一个表的两个记录?

时间:2014-12-01 15:14:23

标签: .net sql-server entity-framework

我使用的是Sql Server,EF和MVC 我有一些像

这样的表
 Product
  Id          (int,PK)
  Supplier    (int,FK)
  ProductName (varchar)

我想映射多个产品,因此当我查询产品时可以找到其他供应商的等效产品。

我正在尝试为地图添加另一个表格。

  ProductMap
     ProductId      (int)
     Supplier       (int)
     OtherProductId (int)

但这种方式很难查询。那么还有更好的方法吗?

2 个答案:

答案 0 :(得分:0)

你不会这样查询吗?:

SELECT  p.Id ,
        p.Supplier ,
        p.ProductName ,
        pm.Supplier ,
        pm.OtherProductId
FROM    Product p
        INNER JOIN ProductMap pm ON p.ID = pm.ProductId

答案 1 :(得分:0)

你的问题很模糊,但我想我知道你在追求什么。

如果您的“产品”是可以从多个供应商处购买的相同产品,那么您只需要存储一次产品。作为一个类,看起来像这样:

class Product
{
    public int Id { get; set; }
    public string ProductName { get; set; }
    public List<Supplier> Suppliers { get; set; }
}

作为SQL表,看起来像这样:

Product                    
    ProductId       (int)
    ProductName     (varchar)

ProductSupplier
    ProductId       (int)
    SupplierId      (int)

Supplier
    SupplierId      (int)
    SupplierName    (varchar)

所以现在你有从产品到拥有该产品的供应商的一对多关系,并且因为你正在使用实体框架,你的查询在C#中是这样的:

var suppliers = myDbContext.Products
                    .Single(p => p.ProductName == "product")
                    .Suppliers.ToList();

这会为您提供每个提供该产品的人员的清单。如果不同的供应商有不同的价格,那么只需在Price表格中添加ProductSupplier列,即可存储该供应商销售此产品的价格。

如果您的“产品”不是100%完全相同,并且您正在寻找其他人销售的类似产品,那么您需要类似的东西,而是您拥有产品“类别”(或“类型”或任何您想要称它们用于存储被认为是等价的东西。从那里,您的Product将拥有ProductCategoryId外键,因此对于给定的产品,您可以查找其类别以查找所有等效项。作为一个类,看起来像这样:

class Product
{
    public int Id { get; set; }
    public string ProductName { get; set; }
    public Supplier Supplier { get; set; }
    public Category Category { get; set; }
}

作为SQL表,这将是这样的:

Product                    
    ProductId       (int)
    ProductName     (varchar)
    CategoryId      (int)
    SupplierId      (int)

ProductCategory
    Id              (int)
    Description     (varchar)

Supplier
    SupplierId      (int)

同样,EF使查询非常简单:

var similarProducts = myDbContext.Products
                    .Single(p => p.ProductName == product")
                    .Category.Products.ToList();