2012-08-15 131 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

相關問題