Der Grund, warum ich nicht einfach zwei separate Abfragen für Produkte und Etiketten durchgeführt habe, ist, dass es bei N Produkten N zusätzliche SQL-Abfragen für Etiketten gibt (und N könnte groß sein).
Hinweis: .AsExpandable() und .Invoke() stammen aus LinqKit Core, sodass verschachtelte Ausdrücke von Linq korrekt übersetzt werden können Sql.) Außerdem verwende ich .NET Framework 4.8 mit Entity Framework 6.
Unten ist der Code, den ich jetzt habe (und die generierte SQL-Abfrage sieht gut aus. Kein N+1-Problem.) Gibt es überhaupt eine Möglichkeit, die Zuordnungslogik zu extrahieren? (Ich bin offen für die Verwendung von AutoMapper, wenn das der richtige Weg sein sollte.)
Code: Select all
/*DAO methods*/
public List ListProductsFilteredByLabelCustomerID
(string productType, string customerID)
{
return context.Product
.AsExpandable()
.Where(product => product.ProductType == productType)
.Select(ToDTOFilteredByLabelCustomerID(customerID));
}
public List ListProductsFilteredByLabelCustomerType
(string productType, string customerType)
{
return context.Product
.AsExpandable()
.Where(product => product.ProductType == productType)
.Select(ToDTOFilteredByLabelCustomerType(customerID));
}
/*Projection Expressions*/
public static Expression
ToDTOFilteredByLabelCustomerID(string customerID)
{
return product => new ProductLabelsDTO {
// I hope to extract these assignments
productName = product.Name,
productDescription = product.Description,
productSKU = product.SKU,
// skipped bunch of other product's fields for simplicity...
//
Labels = product.Labels
.Where(label => label.CustomerID == customerID)
.Select(label => LabelDTO.ToDTO().Invoke(label))
};
}
public static Expression
ToDTOFilteredByLabelCustomerType(string customerType)
{
return product => new ProductLabelsDTO {
// I hope to extract these assignments
productName = product.Name,
productDescription = product.Description,
productSKU = product.SKU,
// skipped bunch of other product's fields for simplicity...
//
Labels = product.Labels
.Where(label => label.CustomerType == customerType)
.Select(label => LabelDTO.ToDTO().Invoke(label))
};
}
Mobile version