Entity Framework 4 Code First and the new () operator

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 ...

+6
entity-framework-4 poco code-first
source share
1 answer

Here are a few points that may help answer your question:

In your classes, you have a field for a collection of children and a method for adding to children. EF in general (and not just Code First) currently requires collections to be surface as properties, so this template is not currently supported. More flexibility in how we interact with classes is a common EF request, and our team is looking at how we can support this at the moment.

You mentioned that you need to explicitly register objects with context, this is not necessary. In the following example, if GetAdam () returned an Adam object that is bound to the underlying context, then a new child Cain will be automatically detected by EF when it is saved and pasted into the database.

var adam = myAdamRepository.GetAdam ();

var cain = new Child ();

adam.Children.Add (Cain);

~ Rowan

+4
source share

All Articles