I am stuck with a stack overflow exception in this section of code, it is obviously occurring because the Customer object calls a list of CustomerBackgroundLevel objects, each one of which creates a new customer object. I am trying to find a way around the issue, any help would be appreciated..
Customer Constructor -
public CustomerVO(Customer item)
{
CustomerID = item.CustomerID;
CustomerName = item.CustomerName;
ECNNumber = item.ECNNumber;
CustomerBackgroundLevels = item.CustomerBackgroundLevels.Select(c => new CustomerBackgroundLevelVO(c)).ToList();
}
Customer Background Level Constructor -
public CustomerBackgroundLevelVO(CustomerBackgroundLevel item)
{
CustomerBackgroundLevelID = item.CustomerBackgroundLevelID;
CustomerID = item.CustomerID;
BackgroundLevelID = item.BackgroundLevelID;
StartDate = item.StartDate;
EndDate = item.EndDate;
Customer = new CustomerVO(item.Customer);
BackgroundLevel = new BackgroundLevelVO(item.BackgroundLevel);
}
Customer Get Method -
public CustomerVO GetByID(int id)
{
var item = repository.AsQueryable().Where(x => x.CustomerID == id).FirstOrDefault();
if (item == null)
return null;
return new CustomerVO(item);
}
CustomerBackgroundLevelVOthat takes aCustomerVO. Then you can just directly assign it toCustomerBackgroundLevelVO.Customerrather than instantiating a new one. Your Linq call in theCustomerVOconstructor would then look like:CustomerBackgroundLevels = item.CustomerBackgroundLevels.Select(c => new CustomerBackgroundLevelVO(c, this)).ToList()which will avoid the infinite loop. This only makes sense though if you A) want to reuse the sameCustomerVOobject, and B) don't mind passing a not fully initialized object.FactoryorBuilderobject to create/wire these objects for you and avoid all the nested/recursive interdependencies altogether.