Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework 对自引用表中的数据进行排序_Entity Framework_Entity Framework 4_Ef Code First - Fatal编程技术网

Entity framework 对自引用表中的数据进行排序

Entity framework 对自引用表中的数据进行排序,entity-framework,entity-framework-4,ef-code-first,Entity Framework,Entity Framework 4,Ef Code First,我有一张桌子,可以放一些产品 ProductA ProductB ProductC 其中一个要求是一种产品可以属于另一种产品 ProductA ProductD -> ProductA ProductE -> ProductA ProductB ProductF -> ProductB ProductC 如您所见,属于另一个产品的产品必须位于它的正下方。所有数据必须属于一个列表(无嵌套集合),因为我只需要在一个网格中显示数据 如果我引入一个新的属性ReferenceProd

我有一张桌子,可以放一些产品

ProductA
ProductB
ProductC
其中一个要求是一种产品可以属于另一种产品

ProductA
ProductD -> ProductA
ProductE -> ProductA
ProductB
ProductF -> ProductB
ProductC
如您所见,属于另一个产品的产品必须位于它的正下方。所有数据必须属于一个列表(无嵌套集合),因为我只需要在一个网格中显示数据

如果我引入一个新的属性ReferenceProductId,即指向另一个产品,那么我就解决了“归属”问题,但是我找不到一种方法来对它们进行排序。最简单的方法是如果我可以说ProductA属于ProductA,但如果我没有弄错的话,那是不可能的。此外,当我将一种产品分配给另一种产品时,我不能这样做:

product.ReferenceProductId = anotherProduct.Id
我需要分配一个引用本身,因为我正在使用标识主键,所以新记录的Id将为0

product.ReferenceProduct = anotherProduct;

你的想法是什么?我可以让它正确地保存数据,但我不能让它按上述排序顺序加载数据。

您可以创建一个自定义比较器来按顺序排列列表。这只是一个示例,但它使用了比较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);
    }
}

因此,基本上,当我从Customer.Invoices[0].Products检索到某个层次结构对象时,我可以自由地将产品指向新集合,EF不会抱怨,是否有任何不希望的后果?ex Customer.Invoices[0].Products=Products.OrderBy(p=>p,new ProductComparer());我不确定我是否理解这条评论——但它不应该抱怨,你只是简单地重新排列了列表,没有改变EyeEP中的任何实体,没有EF的抱怨。这也将解决其他一些问题。:)谢谢
products.OrderBy(p => p, new ProductComparer());