I have a pretty deep hierarchy of objects I'm trying to save with Entity Framework 4, POCO, PI (Persistence Notorance) and Code First. Suddenly, everything began to work very well when it became clear to me that I was not using the new () operator. As originally written, objects often use new () to create child objects.
Instead, I use my method of creating a repository template to create all child objects as needed. For example, given:
class Adam { List<Child> children; void AddChildGivenInput(string input) { children.Add(new Child(...)); } } class Child { List<GrandChild> grandchildren; void AddGrandChildGivenInput(string input) { grandchildren.Add(new GrandChild(...)); } } class GrandChild { }
("GivenInput" implies some processing not shown here)
I define AdamRepository as:
class AdamRepository { Adam Add() { return objectContext.Create<Adam>(); } Child AddChildGivenInput(Adam adam, string input) { return adam.children.Add(new Child(...)); } GrandChild AddGrandchildGivenInput(Child child, string input) { return child.grandchildren.Add(new GrandChild(...)); } }
Now it works quite well. However, I am no longer "ignorant" of the persistence mechanism, since I abandoned the new () operator.
In addition, I am at risk of the anemic domain model , because so much logic ends in the repository, and not in the domain objects.
After a long farewell, the question is:
Or a few questions ...
- Is this template required to work with EF 4 Code First?
- Is there a way to keep using new () and still work with EF 4 / POCO / Code First?
- Is there another template that would leave the logic in the domain object and still work with EF 4 / POCO / Code First?
- Will this restriction be removed in later versions of Code First support?
Sometimes trying to switch to POCO / Perseverance. Ignorant route swimming upstream, at other times like swimming Niagra Falls. However, I want to believe ...
entity-framework-4 poco code-first
Eric J.
source share