Do you ever create a BarModel
without a parent FooModel
? The first thing that comes to my mind is to simply require passing the parent FooModel
into the BarModel
Create
method:
public class ModelFactory
{
public FooModel Create(Foo foo)
{
var fooModel = new FooModel()
{ ... };
// pass this model instance to the Create method
fooModel.Bars = foo.Bars
.Select(b => Create(b, fooModel))
.ToList();
return fooModel;
}
// how about making this private?
// can a Bar exist without a Foo parent?
private BarModel Create(Bar bar, FooModel parentModel)
{
return new BarModel()
{
// we don't create a new model here
Foo = parentModel
};
}
}
On a side note, usual direction of the DAL-Entities dependency is to declare your entities (FooModel
, BarModel
) in your domain model, and have the DAL know about them and return instances of these actual entities. You can have data-specific DAOs (Foo
, Bar
) if you need them for the db access to work properly (although they are rarely needed if you're using an ORM framework), but they should be internal to the data layer, without the need to do these mappings inside your business logic.