2012-08-15 132 views
0

我有一张表,用于存储一些产品。对自引用表中的数据进行排序

ProductA 
ProductB 
ProductC 

一个请求的是一个产品可以属于另一个

ProductA 
ProductD -> ProductA 
ProductE -> ProductA 
ProductB 
ProductF -> ProductB 
ProductC 

正如你所看到的,属于另一种产品的产品必须定位正确娄它。所有的数据都必须属于一个列表(没有嵌套集合),因为我只需要在一个网格中显示数据。

如果我介绍一个新的属性ReferenceProductId,即指向其他产品,那么我解决“归属”的问题,但我无法找到一个方法如何对它们进行排序。 easiset的方式是,如果我可以说ProductA属于ProductA,但如果我没有弄错,那是不可能的。此外,当我分配一个产品到另一个,我不能做到这一点:

product.ReferenceProductId = anotherProduct.Id 

我需要分配基准本身,因为我有身份的主键工作,所以编号为0的新记录。

product.ReferenceProduct = anotherProduct; 

你在这里有什么想法?我可以使它正确保存数据,但我无法按照上述排序顺序加载它们。

回答

2

您可以创建自定义比较的订购列表。这只是一个例子,但它使用了比较Id和参考Id,它允许我实现上面想要的结果,假设referenceId在没有产品参考时为null。如果FK没有通过调用product.Reference.Id进行更新,您可以更改代码,但为了简单起见,我忽略了这一点。

我的产品类别:

public class Product 
    { 
     public int Id { get; set; } 
     public string Name { get; set; } 
     public int? ReferenceId { get; set; } 
    } 

的比较器:

public class ProductComparer : IComparer<Product> 
{ 
    public int Compare(Product product, Product other) 
    { 
     if (product.ReferenceId == null && other.ReferenceId == null) 
      return product.Id.CompareTo(other.Id); 

     if (product.ReferenceId == null && other.ReferenceId != null) 
      return product.Id.CompareTo(other.ReferenceId); 

     if (product.ReferenceId != null && other.ReferenceId == null) 
      return ((int) product.ReferenceId).CompareTo(other.Id); 

     if (product.ReferenceId == other.ReferenceId) 
      return product.Id.CompareTo(other.Id); 

     return ((int) product.ReferenceId).CompareTo((int) other.ReferenceId); 
    } 
} 

那么你会打电话给你收集的东西是这样的:

products.OrderBy(p => p, new ProductComparer()); 
+0

所以基本上,当我取回一些层次结构对象ex Customer.Invoices [0] .Products,我可以自由地将产品指向新的收藏品,EF不会抱怨,并且有任何联合国期望的后果? ex Customer.Invoices [0] .Products = products.OrderBy(p => p,new ProductComparer()); – Goran 2012-08-15 17:53:02

+0

我不确定我是否理解评论 - 但它不应该抱怨,你只是重新排列列表而不更改 – 2012-08-15 18:33:52

+0

中的任何实体。没错,EF没有任何抱怨。这也将解决一些其他问题。 :) 谢谢。 – Goran 2012-08-15 18:34:06

相关问题