当类与第二个类多次相关时,如何在查询中将LINQ表达式用作类的静态成员

当类与第二个类多次相关时,如何在查询中将LINQ表达式用作类的静态成员,linq,entity-framework,asp.net-mvc-4,Linq,Entity Framework,Asp.net Mvc 4,这与我先前的问题有关: 在将静态LINQ表达式添加到我的模型后,当直接从该模型类的可枚举项中进行选择时,我能够在方法样式的LINQ语句中使用该表达式(如上面问题的选定答案和下面的示例所示)。现在,我必须尝试使用一个相关模型中的表达式,并且再次超越了我对LINQ和EF的了解 涉及的简化模型包括: //The model class for Items for sale in the system public class Item { [Key, Column(Order = 0)]

这与我先前的问题有关:

在将静态LINQ表达式添加到我的模型后,当直接从该模型类的可枚举项中进行选择时,我能够在方法样式的LINQ语句中使用该表达式(如上面问题的选定答案和下面的示例所示)。现在,我必须尝试使用一个相关模型中的表达式,并且再次超越了我对LINQ和EF的了解

涉及的简化模型包括:

//The model class for Items for sale in the system
public class Item
{
    [Key, Column(Order = 0)]
    public String CompanyId { get; set; }

    [Key, Column(Order = 1)]
    public String ItemId { get; set; }

    public Int32 CategoryId { get; set; }

    [ForeignKey("CategoryId")]
    public virtual GlobalCategory GlobalCategory { get; set; }

    [ForeignKey("CompanyId, CategoryId")]
    public virtual CompanyCategory CompanyCategory { get; set; }

    //LINQ Expression to coalesce a company specific category alias
    //with the default global category when no alias exists
    public static Expression<Func<Item, String>> linqCategoryName
    {
        get
        {
            return i => (i.CompanyCategory.CategoryAlias == null || 
                         i.CompanyCategory.CategoryAlias == "") ?
                         i.GlobalCategory.CategoryName :
                         i.CompanyCategory.CategoryAlias;
        }
    }
}
Item类的LINQ表达式成员可成功用于此类LINQ语句:

var categories = usscodb.Items.Where(i => i.CompanyId = siteCompanyId)
                               .OrderBy(Item.linqCategoryName)
                               .Select(Item.linqCategoryName)
                               .Distinct();
但是,我不确定在以下情况下如何使用static Item.linqCategoryName:

var categories = db.ItemRelationships
                .Where(ir => ir.RelationshipType.RelationshipTypeName == "Supply"
                    && ir.ParentItem.Active
                    && ir.RelatedItem.Active
                    && ir.ParentItem.CompanyId == siteCompanyId
                    && ir.RelatedItem.CompanyId == siteCompanyId)

                //the linqCategoryName member is not available for use this way
                .Select(ir.ParentItem.linqCategoryName)
                .Distinct();
我想我离这里很近了。我曾尝试使用父项的键将项关系显式地连接到项,然后尝试使用静态LINQ表达式,但我认为由于项关系中存在两个项,LINQ无法确定我想要哪个。我不知道如何明确地告诉LINQ我想从哪个项目使用静态方法。

试试这个:

.Select(ir => ir.ParentItem)
.Select(Item.linqCategoryName)
.Select(ir => ir.ParentItem)
.Select(Item.linqCategoryName)