2013-01-24 198 views
1

我有DTO SUACH的列表爲:嵌套DTO搜索

Public Class UKey 
{ 
    public Int64 Key{ get; set; } 

} 

Public Class Test : UKey 
{ 
    public Int64? CityId { get; set; } 
    public Test2 test2{ get; set; } 
} 
Public Class Test2 : UKey 
{ 
    public Int64? CountryId { get; set; } 
    public Test3 test3 {get;set;} 
} 
public Class Test3 :UKey 
{ 

} 

我有嵌套的DTO,例如類測試具有類試驗2的成員,並且類TEST2具有類型類測試3中,每個成員類有它自己的唯一鍵,這個鍵不能在它們中重複,就像GUID一樣。 我想查詢類測試,找到這些嵌套的Dtos與給定的唯一鍵之一。

回答

1

假設tests對象是IEnumerable<Test>,它是一組Test對象;

tests.SingleOrDefault(q => q.test2.Key == id || q.test2.test3.Key == id); 

更新:您需要應用遞歸搜索。我已經改變了基類,

public class UKey 
{ 
    public Int64 Key { get; set; } 
    public UKey ReferencedEntity { get; set; } 
} 

和搜索功能:

private UKey Search(UKey entity, Int64 id) 
    { 
     UKey result = null; 
     if (entity.Key == id) 
      result = entity; 
     else 
     { 
      result = this.Search(entity.ReferencedEntity,id); 
     } 
     return result; 
    } 
0

答案很可能是用一種形式的recursion:如果你創建你的基類一個FindKey方法並相應地實現它在你的派生類,你可以簡化查詢:

//given: 
//'tests' is a IEnumerable<UKey> 
//'g' = a guid you are looking for 
tests.SingleOrDefault(q => q.FindKey(g)); 

和類的實現可能是這個樣子:

public abstract class UKey 
{    
    public Guid Key{ get; set; } 
    public abstract bool FindKey(Guid g); 
} 

public class Test : UKey 
{ 
    public Int64? CityId { get; set; } 
    public Test2 Test2{ get; set; } 

    public override bool FindKey(Guid g){ 
     return Key == g || (Test2!= null && Test2.FindKey(g)); 
    } 
} 

/*etc.. implement the FindKey method on all you derived classes*/