2013-01-24 152 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*/