将静态 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;
}
}
}
和
//The model class for Item Relationships, used to relate two items
//(a "Parent Item" and "Related Item") such as one is a supply for to the other
public class ItemRelationship
{
[Key]
public Int32 RelationshipId { get; set; }
public Int32 RelationshipTypeId { get; set; }
[ForeignKey("RelationshipTypeId")]
public virtual RelationshipType RelationshipType { get; set; }
public String CompanyId{ get; set; }
public String ItemId{ get; set; }
[ForeignKey("CompanyId, ItemId")]
public virtual Item ParentItem { get; set; }
public String RelatedCompanyId{ get; set; }
public String RelatedItemId{ get; set; }
[ForeignKey("RelatedCompanyId, RelatedItemId")]
public virtual Item RelatedItem { get; set; }
}
Item 类的 LINQ Expression 成员可以成功地与这种 LINQ 语句一起使用:
var categories = usscodb.Items.Where(i => i.CompanyId = siteCompanyId)
.OrderBy(Item.linqCategoryName)
.Select(Item.linqCategoryName)
.Distinct();
但是,我不确定如何在以下情况下使用静态 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 我想从哪个 Item 使用静态方法。