Search for existing suggestions

Create method should initializer collection navigation properties

I've found that in Code First entities, my "many" properties such as

property List<People> SomePropertyName {get; set;}

are null when the entity is instantiated. This breaks the common "convention" of just simply adding entities to the list:

You can't just

You have to do
MyEntity.SomeManyProperty = new List<SomeOtherEntity> { SomeOtherEntityInstance };

but, of course, you can't just do that, because you might wipe out an existing list, if there is one, so you must then do a check first. Ugly.

As a lesser evil, I've resorted to instantiating empty lists in the constructor of my entities but this is a workaround and not in the spirit of conventional use and reduction of unnecessary code. It seems to me that the EF could handle this.

4 votes
Sign in
Sign in with: facebook google
Signed in as (Sign out)

We’ll send you updates on this idea

Will Kalman shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →


Sign in
Sign in with: facebook google
Signed in as (Sign out)
  • Stephen Bognar commented  ·   ·  Flag as inappropriate

    Resharper actually reports this practice of initializing the lists in the constructor as a warning: Virtual member call in constructor.

    Warnings make my code ugly. Please add this feature.

  • Will Kalman commented  ·   ·  Flag as inappropriate

    Thank you for the comments. I see how, since it's a simple POCO class, that I'd have to initialize it if using the "new" keyword. It does throw a slight wrench in the simple conventions idea but it makes sense.

    When I query for an object, I see that the properties are filled with an empty list. So that operates as expected.

    I tried the .Create method from the DbSet and that did not initialize the lists.

    // Empty List properties in this object are initialized
    var test = ctx.People.FirstOrDefault();

    // The same properties here are null even though it's a proxy class and I'd expect that EF would have some hand in property initialization
    var test = ctx.People.Create();

  • Ladislav Mrnka commented  ·   ·  Flag as inappropriate

    Entity is just class and you are responsible for initializing internals of your classes - it is not a workaround to assign list in your constructor (or directly as initializer). It is common and correct practice. As @Diego mentioned EF cannot handle instantiation of your classes if you use new keyword because there is no EF involved. Try to use Create method on your DbSet instead and if you have class enabled for lazy loading you will get collections initialized.

Feedback and Knowledge Base