efcore icon indicating copy to clipboard operation
efcore copied to clipboard

EF Core 1.0 not including columns with default values in insert into query

Open monicadelprado opened this issue 10 years ago • 72 comments

Steps to reproduce

I'm using EF Core 1.0 and I have a model where I design some properties with default values similar to modelBuilder.Entity<Listings>(entity => { entity.Property(e => e.IsActive).HasDefaultValueSql("1");} The table in the database is created correctly defining the columns with the corresponding default value [IsActive] bit NOT NULL DEFAULT 1

The issue

When I add a new entity and save changes in my context, the insert into statement generated does not contain the properties that have default values even though I assign specific values for those properties. The result in the database is a record where the columns with default values doesn't contain the values I passed in my model.

More info on this post http://stackoverflow.com/questions/40619319/entity-framework-not-including-columns-with-default-value-in-insert-into-query/

Further technical details

EF Core version: 1.0 Visual Studio version: VS 2015

monicadelprado avatar Nov 21 '16 22:11 monicadelprado

I think we made some bug fixes around this in 1.1. Could you upgrade to 1.1 and see if the issue is fixed? https://blogs.msdn.microsoft.com/dotnet/2016/11/16/announcing-entity-framework-core-1-1/

rowanmiller avatar Nov 22 '16 18:11 rowanmiller

I have upgraded to EF Core 1.1.0 and still have the issue

monicadelprado avatar Nov 22 '16 23:11 monicadelprado

@mdelprado-emphasys This looks like a dupe of #6054. If you need a bool with a store-generated default, then use a nullable bool. This gives EF a way to distinguish between not set (null) set to false and set to true.

ajcvickers avatar Nov 23 '16 00:11 ajcvickers

@ajcvickers do you think there is an opportunity here for a model validation error or warning?

divega avatar Nov 23 '16 02:11 divega

@divega Yes, I think that would be a good idea.

ajcvickers avatar Nov 23 '16 02:11 ajcvickers

@divega what kind of error or warning were you talking about? And what about DateTime InsertDate with default value of GetUtcDate()? I really don't want to make InsertDate nullable.

BTW, I'm not sure what exactly did people expect to happen with boolean with default value of true... Did they expect EF to change the C# / CLR spec?

gdoron avatar Nov 23 '16 08:11 gdoron

@gdoron we need to do more analysis but I think the warning would only apply to Boolean properties.

When you specify that a property has a default value in the database, EF Core will use the default value of the CLR type as an indication that it should let the database set the default value, hence it won't include the column in the INSERT operation.

But Boolean properties only have two states, so it is unlikely that you would intend any of these two values to mean "leave the column alone":

  • If you configure the default to be "1" it becomes impossible to insert a "0"
  • Configuring the default to be "0" is pointless

divega avatar Nov 23 '16 09:11 divega

@divega

But Boolean properties only have two states ...

This is why I don't get what did they expect to happen, and they may expect a similar thing with numeric properties too, I assigned my property 0 but it's being ignored.
(I'm assuming default(DateTime) wouldn't bother them as its value isn't considered to be "valid")

gdoron avatar Nov 23 '16 11:11 gdoron

@gdoron , @divega It makes sense, now that you mention, that if I don't have a nullable type, the EF just adds the default value, but I was actually expecting the same behavior than when I do an INSERT INTO directly in the database. The INSERT INTO just adds the record with the values I send in the query and ignores the default values.

monicadelprado avatar Nov 23 '16 13:11 monicadelprado

@mdelprado-emphasys That's because SQL doesn't have the limitation there actually is a property that being sent.

gdoron avatar Nov 23 '16 13:11 gdoron

IMO, when a property is not nullable, the HasDefaultValue(Sql) instruction should be ignored when it comes to setting property values, not for migrations. This gives users the opportunity to create the database schema as they like (i.e. with defaults), but they won't be surprised by this rather unexpected behavior. It's easier to understand that a non-nullable property always has a value (so setting a default by EF isn't necessary) than that a value is overwritten when it happens to have been set to the CLR default.

GertArnold avatar Nov 23 '16 16:11 GertArnold

@GertArnold It would be very annoying having DateTime? InsertDate all over the place just because people make mistakes. But regardless, I believe it's too late for changing as it's a huge breaking change. Maybe for EF Core Core. 😸

gdoron avatar Nov 23 '16 16:11 gdoron

@gdoron I see your point. But people are going to tack HasDefaultValue to required properties other than InsertDate and such. That's common practice, for example to be able to add required columns to existing tables. For any required property of which the type's default value makes sense (i.e. not DateTime, usually) this causes the insane behavior that an entity with (CLR) default values can't be stored correctly if the defined default differs from the CLR default. Unless ValueGeneratedNever is applied. Do we expect people to understand (or even know) all that? For one, it's not in in the docs on HasDefaultValue.

GertArnold avatar Nov 23 '16 21:11 GertArnold

There seems to be more useful information in this issue now than in the original #6054, so closing that one as a duplicate of this one.

divega avatar Nov 23 '16 23:11 divega

@GertArnold that is an interesting insight. I do agree that currently you need to understand a lot before you can make some of these scenarios work correctly.

However as @AndriySvyryd pointed out in a recent conversation, ValueGeneratedNever is not even the right solution in this case: if you were to set that, the value you configured in HasDefaultValue() or HasDefaultValueSql() would never be used.

Instead what we are looking at is to introduce a warning (on second thought, besides bool it should also probably apply to properties of enum types) which suggests making the property of a nullable type. If the property is nullable then the default value of the CLR type will be null, which is hopefully outside of the domain of values you intend to store in the database and hence a better choice of a "sentinel value" to indicate that the value will be generated in the store.

In fact in most cases if you have ValueGeneratedOnAdd and a nullable type it would probably make sense to make the property IsRequired(true) at the same time. We could even consider introducing this as a convention or otherwise include it in the warning mentioned above.

We have considered other options, e.g.:

  • Having a way to configure a different "sentinel" value from the default value for the CLR type to decide whether the value should be sent to the database on INSERTs (I remember vaguely but I think we either had this and we removed it at some point or we were very close to implementing it and then we decided not to do so).
  • Having a way to configure that the default CLR type should not be used as a sentinel, and that the decision to send the value to the database should be made merely on whether the property value is marked as temporary.

But these options seem to lead to a more complicated experience or mental model and not necessarily help as much as making the property of a nullable type.

cc @ajcvickers

divega avatar Nov 23 '16 23:11 divega

@ajcvickers to split this out into some separate actionable items

rowanmiller avatar Nov 28 '16 19:11 rowanmiller

Created #7163, #7165, and #7199.

ajcvickers avatar Dec 07 '16 18:12 ajcvickers

@ajcvickers I understand your comment in #7347 but this is not a valid long term solution. Let me explain the scenario (nothing to do with migrations).

I have an entity, it has a required boolean IsActive property in the domain object that is used by the DbContext. However, in many cases this field is not included on dynamic objects that represent a subset of the domain (e.g. id, code, name) so when a save is performed (on a new dynamic object) I expect the IsActive to be set to true since it is not a nullable, but not a field in the object passed to the DbConext.

Another similar scenario would be a CreateDate audit field that can't be nullable but should be set by the database when inserted, or a LastChanged audit field when the record is created/updated, again can't be nullable.

In the case of migrations for existing tables. If I add a migration to add a new required column called bool IsActive, I instantly fall back into the same problem above. So I don't feel that this issue is closed, but instead redefines the meaning of Default values.

It is quite feasible to have a required field with a default, and supply a value on insert. If a value is supplied it should always be used, and only when a value is not supplied, should the default be used. This is what Default Values used to mean.

Allann avatar Jan 05 '17 02:01 Allann

@Allann I am not sure the scenario you are describing is what I have in mind, but consider that you can at the same time:

  • make the property of type bool?
  • configure the property as IsRequired()

That way the property on the entity can be null (meaning no value was supplied and the default specified in the model should be used on new inserted rows) but the column created will not be nullable.

divega avatar Jan 05 '17 02:01 divega

@divega You are completely correct in that that will "work-around" the issue, however, I don't want the domain object to rely on a particular database mapping to work. I NEED the field to be not nullable as it is not allowed to be null. What you are suggesting is the field is allowed to be null at some stage, as long as it's set before being sent to the database. My viewmodel field is nullable, but that is a particular user/UX scenario and doesn't normally require these fields. But the dto and domain classes both have this set as bool not nullable.

Note: I use code first via a domain class and a separate mapping class. I would need to set the domain object field to nullable, and remember to set the mapping for that field to required. This would have been implied if the field remained non-nullable.

As an aside this is new in EF core as behaves differently in EF6. This means that many will have to change their code base when moving to EF core.

Much of our legacy code relies on primitive types with database defaults, having to change all these to nullable will be a huge task especially since this is a hidden side-effect and not expected behavior. If I set a value on a field, I expect that value to be inserted into the database and not have it overridden by a default constraint when inserted into the database.

If this is to be the "rule", then I highly recommend putting an exception in the database generation logic that states that ALL fields with defaults NEED to map to nullable properties. Either that, or ignore default values when set against non-nullable properties.

Allann avatar Jan 05 '17 03:01 Allann