Reputation: 404
I have two Domain classes:
var ParentClass
{
public Guid Id { get; set; }
public virtual IEnumerable<ChildClass> Children { get; set; }
}
var ChildClass
{
public Guid Id { get; set; }
public Guid ParentId { get; set; }
public virtual ParentClass Parent{ get; set; }
}
how can I get a list of ParentClass an map it and all of it's children to two predefined view models('PClass' to map ParentClass & 'ChClass' to map ChildClass)?
I tried this code but it seems not working:
var query = MyDataContext.ParentClasses.Select(x => new PClass
{
Id = x.Id,
Children = x.Children.Select(y => new ChClass // this select is not working
{
Id = y.Id,
ParentId = y.ParentId,
Parent = x // x is not the right type and it should be of type 'PClass'
})
}).ToList();
Upvotes: 1
Views: 796
Reputation: 30464
If every PClass
has zero or more Children, it is fairly useless to fill in the parent of every Child class, because you already know that it is PClass.
Besides, this Parent in the ChildClass has at least one Child with a PClass in it which of course has at least one child with a Parent who has at least one Child with has a Parent, ... when do you want to stop?
So in such cases, we either tend not to provide a property to the Parent, or give it a null value:
var query = MyDataContext.Parents.Select(parent => new PClass
{
Id = parent.Id,
Children = parent.Children.Select(child => new ChClass
{
Id = child.Id,
// ParentId = y.ParentId, Useless, you know it has the same value as Id
// Parent = ... useless, you know it has the same value as the parent
// that you are creating.
})
.ToList(),
});
Upvotes: 1