我想強類型使用linq to sql查詢3個ef對象。與產品和類別有一對多的關係。我的類包含導航屬性,看起來像這樣。我如何查詢導航使用linq到SQL的特性和ef
public partial class Product
{
public int ID {get;set;}
public string Name {get;set;}
public virtual ICollection<Group> NpGroup {get;set;}
}
public partial class Category
{
public int ID {get;set;}
public string Name {get;set;}
public virtual ICollection<Group> NpGroup {get;set;}
}
public partial class Group
{
public int ID {get;set;}
public int ProductID {get;set;}
public int CategoryID {get;set;}
public virtual Product NpProduct {get;set;}
public virtual Category NpCategory {get;set;}
}
試圖避免基於.INCLUDE()的字符串,我將如何構建一個返回一組等於產品ID「1」,但也包含在產品和類別的名稱查詢?
喜歡的東西:
var context = ObjectContext.CurrentObjectContext;
var query = from c in context.Group
where c.ProductID == 1
//Include the names of the product and category of the group record (c.NpProduct.Name etc.)
select c;
我可能丟失穿過森林樹木,但我似乎無法得到ObjectContext.LoadProperty的語法(如果這是正確的方式去)。
有什麼想法?謝謝。
我已經試過您的兩個建議,我想我的問題是我的名單的返回類型檢查。在我上面的例子中,我試圖從('映射像')組對象引用中獲得每個產品及其屬性。我需要使用某種foreach循環嗎?感謝您的迴應。 –
trevorc
2010-10-04 21:31:35
是的,你的上面的查詢是'select c' - c是你的查詢中的一個別名。這只是一個IQueryable,我假設你正在做。最後ToList將把查詢投影到一個'List'中。您需要將投影更改爲您想要返回的內容。如果您需要產品,請從產品中選擇,而不是組(如您在查詢中所做的那樣)。 –
RPM1984
2010-10-04 22:31:27