I have a object model like this
public class Parent{
public int Id;
public string Name;
public Child Sibling
}
public class Sibling {
public int Id;
public string Name;
public Cousin Cousin
}
public class Cousin{
public int Id;
public string Name;
public DateTime CreatedDate;
}
I’m trying to flatten or project? it to a model like this
public class ViewModelSibling {
public int Id;
public string Name;
}
public class ViewModel{
public int ParentId;
public string ParentName;
public ViewModelSibling Sibling;
public ViewModelSibling Cousin;
public DateTime? CousinCreatedDate;
}
where Sibling and Cousin are Nullable
ControllerCode
[HttpPost]
public virtual ActionResult GetGridItems()
{
IQueryable<Parent> parents = GetParentsWhereCriteriaMet();
var data = parents.Select( p => new ViewModel{
ParentId = p.Id,
ParentName = p.Name,
Sibling = new ViewModelSibling { Id = p.Sibling.Id, Name = p.Sibling.Name},// if p.Sibling is null and exception is thrown
Cousin= new ViewModelSibling {Id =p.Sibling.Cousin.Id, Name = p.Sibling.Cousin.Name}// if p.Sibling or p.Sibling.Cousin are null and exception is thrown
CousinCreatedDate = p.Sibling.Cousin.CreatedDate
} )
return new JsonResult { Data = data };
}
I’m trying to avoid using ToList() because I don’t want all of the Parent records to be returned. The ViewModel is going to be bound to a Telerik Grid using Ajax, this handles the paging.
I don’t want to use AutoMapper because I don’t want all fields and records to be returned.
How do I flatten this model without using ToList()?
Use either
or
depending on your requirements.
etc…