1

Is there ANY way to initialize a property in an Entity Framework entity that has a collection?

This is the generated code for an Entity that has a collection:

public partial class MyEntity
{
    public MyEntity()
    {
       this.MySubEntities = new HashSet<MySubEntity>();
    }

    public bool IsActive {get; set;}
    public virtual ICollection<MySubEntity> MySubEntities {get; set;}
}

If I need to make a new MyEntity that I want to default to IsActive = true, it cannot be done! (Unless I edit the T4 template.)

Please tell me there is a way to default IsActive = True without editing the generated file (or the T4).

Note: I have AutoMapper making the entity for me, so new MyEntity {IsActive = true} will not work.

Vaccano
  • 78,325
  • 149
  • 468
  • 850

3 Answers3

0

Without editing the T4, I don't see what you can do.

So you could change your T4 to generate something like that (initialize null lists in getter instead of doing that in ctor)

private ICollection<MySubEntity> mySubEntities_;
public virtual ICollection<MySubEntity> MySubEntities {
   get {
        return mySubEntites_ ?? (mySubEntites_ = new HashSet<MySubEntity>());
   }
   set {
       mySubEntities_ = value;
   }
}

then you wouldn't need the empty ctor in the generated class, and could have a partial class with an empty ctor, doing what you need

public MyEntity() {
   IsActive = true;
}
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
0

I'm not sure... but I will give you some directions so you can take a look.

If you set your default value on your database to IsActive = true I believe EF handles this by itself. If not, I'm pretty sure you can set the default value on the Designer.

I think you can also do another constructor because this are partial classes.

you might read this :How to set default value for POCO's in EF CF? may give you more insight.

another solution, (practical but not good and didn't answer the question), is to change IsActive to IsInactive so it defaults to false :D - I really do this when design databases.

Community
  • 1
  • 1
Bart Calixto
  • 19,210
  • 11
  • 78
  • 114
0

You can edit the EF model to add default values. In the properties of a column you can find "Default value" and set it to what you want. It is default set to "(None)".

Kobbe
  • 809
  • 5
  • 16