2015-07-02 24 views
0
public class MyObj 
{ 
    [Key] 
    public int id {get; set;} 
    public string test1 {get; set;} 
    public string test2 {get; set;} 
    public int test3 {get; set;} 
    public int test4 {get; set;} 
    public int test5 {get; set;} 
    public int? test6 {get; set;} 
    public DateTime? test7 {get; set;} 
    public string test8 {get; set;} 
    public string test9 {get; set;} 
    public string test10 {get; set;} 
    public string test11 {get; set;} 
    public string test12 {get; set;} 
    public DateTime? test13 {get; set;} 
    public DateTime? test14 {get; set;} 
    public DateTime? test15 {get; set;} 
    public string test16 {get; set;} 
    public string tes17 {get; set;} 
    public int test18 {get; set;} 
    public DateTime? test19 {get; set;} 
    public bool test20 {get; set;} 

    [ForeignKey("test3")] 
    public virtual Child1 child1 { get; set; } 
    [ForeignKey("test4")] 
    public virtual Child2 child2 { get; set; } 
    [ForeignKey("test5")] 
    public virtual Child3 child3 { get; set; } 
    [ForeignKey("test18")] 
    public virtual Child4 child4 { get; set; } 

    public virtual ICollection<Child1> child5 { get; set; } 
} 


var myobj = unitwork.myobjRepository.get(); 

我只是想拉ID和測試1 test20,沒有child1,child2,child3,child4和child5。C#,實體框架,LINQ如何排除屬性

現在,我做的,

myobj.Select(x => new { 
    id = x.id, 
    test1 = x.test1 
    ... 
    ... 
    test20 = x.test20 
})); 

,但我不認爲這是正確的方式。請告訴我,

+1

是什麼讓你覺得這是錯的? –

+0

,因爲要排除5,需要選擇每個20 ...? –

+0

沒有辦法從類型中「刪除」屬性。您可以將它們的值設置爲null或默認值,但不能刪除它們。 –

回答

2

如果屬性名相同也可能是略有簡單:

myobj.Select(x => new { 
    x.id, 
    x.test1 
    ... 
    ... 
    x.test20 
})); 

如果你只是伸出沒有改造匿名類型將使用相同的屬性名稱的屬性。

如果您很在意創建一個匿名類型,那麼你可以創建只有您需要的屬性和項目命名類型,但沒有什麼錯誤使用匿名類型從你已經顯示。

0

你想這麼做的原因是什麼?如果你正在考慮不要重載sql server,你應該檢查延遲加載。 child1,child2,child3,child4,child5將不會被加載,直到您訪問這些屬性,並且您將有MyObj類(對象)可用。如果你像你這樣做,你最終會得到一個無與倫比的物體。在某些情況下可能會好,但在其他情況下則可能沒有。 也可能是一個解決方案是創建另一個類沒有unnecesery字段,並選擇到該新類的實例。

myobj.Select(x => new NewClass() { 
id = x.id, 
test1 = x.test1 
... 
... 
test20 = x.test20 
}));