Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework POCO default constructor

Is it okay to have default constructor which sets some default values like:

public class BetScreenshot
{
   ...

   public BetScreenshot()
   {
       CreationDateTime = DateTime.UtcNow;
       StatusEnum = BetScreenshotStatus.NotProcessed;
   }
}

My first bad feeling is that these properties might be marked as modified during EF entities instantiation. But may be there is something else?

like image 315
SiberianGuy Avatar asked Aug 25 '11 12:08

SiberianGuy


People also ask

Does EF Core use constructor?

It's possible to define a constructor with parameters and have EF Core call this constructor when creating an instance of the entity. The constructor parameters can be bound to mapped properties, or to various kinds of services to facilitate behaviors like lazy-loading.

What is POCO class in Entity Framework?

A POCO entity is a class that doesn't depend on any framework-specific base class. It is like any other normal . NET CLR class, which is why it is called "Plain Old CLR Objects". POCO entities are supported in both EF 6 and EF Core.

Does EF core need empty constructor?

Keeping objects complete and valid all the time is strategy used in different methodics. It's perhaps most popular in Domain Driven Design (DDD). Entity Framework Core 2.1 made big step forward on supporting entities that doesn't have default empty constructor.

How do I set the default value in Entity Framework?

You can set "StoredGeneratedProperty" attribute of table column in the EDMX file to Computed to enable default value insertion in entity framework.


1 Answers

Yes it's ok to initialize properties. Effectively during construction using a parameterless constructor, the fields of the type are initialized to the default anyway. You're just choosing a different default. It's a pretty common practice to new up child entities and collections, but there's no reason simple properties can't be initialized. I do this for several entities and EF correctly recognizes the object as new/unmodified.

like image 158
Kit Avatar answered Sep 30 '22 10:09

Kit