Entity Framework Core 2.x default value

.net-core entity-framework-core


In the official documentation I can see to set the default value on a property of my model it is only by Fluent API (no data annotation).

            .Property(b => b.Rating)

In the other hands I saw in a video tutorial the author set the default value in the same property:

public int Rating { get; set; } = 3;

I tested both with same result. It's correct to use the second approach? What is better?

Thanks in advance

4/19/2018 3:48:44 PM

Popular Answer

When you use HasDefaultValue API, you are configuring your database to generate value when none is provided during INSERT statement. This will generate the value, regardless of you use EF or raw SQL or directly write insert statement in SSMS.

When you set default value in CLR type, your database won't be configured. So instead of server generating values, you are essentially generating values on client. When you initialize new Blog without setting rating, it will have value of 3 which EF will save to database unless set otherwise. This client side generation means that you need to have Rating column in your insert statement and provide a value from client when inserting the record.

What is better?

It entirely depend on use case and the value generation. If you are not inserting data outside of EF then it would only change internal processing of insert in EF. Server-side generation mean EF will skip the column in insert but read back value from server after saved. Client-side generation mean that EF will send the column in insert statement. Also the value of 3 is not complex enough to differentiate the usefulness. If you want to generate values which only server can determine, e.g. CreationTime or some server function over other columns or rows, then you cannot write client equivalent.

At the end, if you have both options available, its upto you how you want to configure your database. You can pick any, it wouldn't make huge difference while using with EF Core.

4/23/2018 6:33:44 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow