嵌套的 DTO 搜索

本文关键字:搜索 DTO 嵌套 | 更新日期: 2023-09-27 17:55:46

我有DTO Suach列表:

 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 的成员,类测试2 有一个类型类测试 3 的成员,每个类都有自己的唯一键,这个键不能在其中任何一个重复,比如 GUid。我想查询类测试以查找具有给定唯一键的这些嵌套 Dtos 之一。

嵌套的 DTO 搜索

假设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;
    }

答案可能是使用一种递归形式: 如果在基类上创建一个 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*/