Linqkit:防止循环引用和堆栈溢出



我使用带有EntityFrameWorkCore的LinqKit来创建具有单个元素投影的投影。但由于有些模型是嵌套的,我得到了堆叠流。我试图在Projection方法(bool-mapCollusions(中添加一个条件来防止这种情况发生,但它似乎被忽略了。有人知道如何防止这些循环引用吗?

public static Expression<Func<Transport, TransportModel>> GetMainProjection()
{
return transport => new TransportModel()
{
Inmate = transport.Inmate != null ? InmateProjectionsGetProjection(true).Invoke(transport.Inmate) : null,
};
public static Expression<Func<Inmate, InmateModel>> InmateProjectionsGetProjection(bool mapCollusions)
{
return inmate => new InmateModel()
{
Collusions = mapCollusions ? inmate.Collusions.AsQueryable()
.Select(collusion => CollusionProjectionsGetProjection(false).Invoke(collusion))
.ToList() : null     
};
}
public static Expression<Func<Collusion, CollusionModel>> CollusionProjectionsGetProjection(bool mapInmate)
{
return collusion => new CollusionModel()
{
Inmate = mapInmate ? InmateProjectionsGetProjection(false).Invoke(collusion.Inmate) : null,
};
}

尝试以下实现:

public static Expression<Func<Transport, TransportModel>> GetMainProjection()
{
return transport => new TransportModel()
{
Inmate = transport.Inmate != null ? InmateProjectionsGetProjection(true).Invoke(transport.Inmate) : null,
};
}
public static Expression<Func<Inmate, InmateModel>> InmateProjectionsGetProjection(bool mapCollusions)
{
if (!mapCollusions)
return inmate => new InmateModel();
return inmate => new InmateModel()
{
Collusions = nmate.Collusions.AsQueryable()
.Select(collusion => CollusionProjectionsGetProjection(false).Invoke(collusion))
.ToList()
};
}
public static Expression<Func<Collusion, CollusionModel>> CollusionProjectionsGetProjection(bool mapInmate)
{
if (!mapInmate)
return collusion => new CollusionModel();
return collusion => new CollusionModel()
{
Inmate = InmateProjectionsGetProjection(false).Invoke(collusion.Inmate),
};
}

最新更新