Linq-запрос, чтобы получить список продуктов, каждый со списком идентификаторов и списком свойств - PullRequest
0 голосов
/ 28 мая 2018

Я пытаюсь составить список товаров с общим ProductGroupId.Каждый продукт имеет любое количество идентификаторов (например, номер продукта, EAN, ISBN и т. Д.) И любое количество свойств (например, цвет, рост, размер и т. Д.).Каждое свойство имеет любое количество выбираемых параметров (например, «красный», «зеленый» и т. Д. Для цвета).

Продукты хранятся в Products.

Идентификационные метки ("EAN "," ISBN "и т. Д.) Хранятся в ProductIdentifiers, а значение продукта для идентификатора сохраняется в IdentifiersForProducts.Например: EAN (метка): 7044304034373 (значение).

Метки свойства (например, «Цвет») хранятся в ProductProperties, доступные параметры для свойства («Красный», «Зеленый» и т. Д.).) хранятся в ProductPropertyOptions, а выбранный идентификатор опции продукта для определенного свойства сохраняется в PropertyOptionsForProducts.

Вот модели:

Product

public class Product
{
    public int Id { get; set; }
    public int ProductGroupId { get; set; }
    public int ProductGroupSortOrder { get; set; }

    public string Title { get; set; }
    public string Info { get; set; }
    public string LongInfo { get; set; }
    public decimal Price { get; set; }
    public int Weight { get; set; }
    public int ProductTypeId { get; set; }


    // Selected property options for this product
    public ICollection<PropertyOptionForProduct> ProductPropertyOptionForProducts { get; set; }

    // Product identifiers (EAN, ISBN, product number, etc.)
    public ICollection<IdentifierForProduct> IdentifierForProducts { get; set; }

    // ... some more properties
}

Идентификаторы

public class ProductIdentifier
{
    public int Id { get; set; }
    public string Label { get; set; }
    public string Description { get; set; }
    public int SortOrder { get; set; }

    public List<IdentifierForProduct> ProductIdentifiers { get; set; }
}

public class IdentifierForProduct
{
    public int Id { get; set; }
    public int ProductId { get; set; }
    public int ProductIdentifierId { get; set; }
    public string Value { get; set; }

    public ProductIdentifier ProductIdentifier { get; set; }
    public Product Product { get; set; }
}

Свойства

public class ProductProperty
{
    public int Id { get; set; }
    public string Label { get; set; } // E.g. "Battery capacity"
    public string Description { get; set; }
    public string Unit { get; set; } // E.g. "mA"
    public bool AllowMultipleSelections { get; set; }
    public int OptionType { get; set; } // string, single number or from-to range?
    public int SortOrder { get; set; }

    // A property can have multiple options
    public List<ProductPropertyOption> Options { get; set; }
}

public class ProductPropertyOption
{
    public int Id { get; set; }
    public int ProductPropertyId { get; set; }
    public int SortOrder { get; set; }
    public string StringValue { get; set; }
    public decimal NumberValue { get; set; }
    public decimal RangeFrom { get; set; }
    public decimal RangeTo { get; set; }

    public ProductProperty Property { get; set; }
    public ICollection<PropertyOptionForProduct> PropertyOptionForProducts { get; set; }
}

public class PropertyOptionForProduct
{
    public int Id { get; set; }
    public int ProductId { get; set; }
    public int ProductPropertyId { get; set; }
    public int ProductPropertyOptionId { get; set; }

    // Nav.props.
    public Product Product { get; set; }
    public ProductPropertyOption ProductPropertyOption { get; set; }
}

Мой текущий запрос монстра Франкенштейна выглядит такэто:

List<Product> GroupMembers = await (
    from prod in _context.Products
    join ident in _context.IdentifiersForProducts on prod.Id equals ident.ProductId
    join prop in _context.PropertyOptionsForProducts on prod.Id equals prop.ProductId
    where
        prod.ProductGroupId == groupId &&
        prod.Id == ident.ProductId &&
        prod.Id == prop.ProductId
    select prod)
    .Distinct()
    .OrderBy(o => o.ProductGroupSortOrder)
    .ToListAsync();

Я также попробовал кое-что попроще:

List<Product> GroupMembers =
        await _context.Products
            .Include(i => i.IdentifierForProducts)
                .ThenInclude(i => i.ProductIdentifier)
            .Include(po => po.ProductPropertyOptionForProducts)
                .ThenInclude(o => o.ProductPropertyOption)
                    .ThenInclude(p => p.Property)
            .Where(g => g.ProductGroupId == groupId)
        .OrderBy(o => o.ProductGroupSortOrder)
        .ToListAsync();

... но результат был почти таким же, и не правильным.Кажется, я получаю все идентификаторы для всех продуктов в группе по каждому продукту, так что, например, один продукт в группе получает список номеров продуктов, каждый из которых принадлежит каждому из продуктов в группе.И я не получаю никаких свойств ни от одного из двух запросов.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...