1

I have a DB that has constraints on non-nullable fields.

Let's look at just one: ModifiedDate.

The constraint defaults to getdate() when not supplied a value in an INSERT command.

My code is using Entity Framework so I craft up an entry object, create a datetime instance, set its ModifiedDate field, then execute context.SaveChanges() and it works fine.

However, if I create the object and don't set entry.ModifiedDate then context.SaveChanges() fails before the constraint could set a default value

1
  • Non-nullable field should have value. So assign default value at database level instead of entity framework. Commented Jun 30, 2017 at 14:38

1 Answer 1

3

In your entity class you could annotate your ModifiedDate property with the following:

[DatabaseGenerated(DatabaseGenerationOption.Computed)]
public DateTime ModifiedDate { get; set; }

From BOL: DatabaseGenerated

An important database features is the ability to have computed properties. If you're mapping your Code First classes to tables that contain computed columns, you don't want Entity Framework to try to update those columns. But you do want EF to return those values from the database after you've inserted or updated data. You can use the DatabaseGenerated annotation to flag those properties in your class along with the Computed enum.

Sign up to request clarification or add additional context in comments.

5 Comments

You can also do this from the .edmx designer. Select your DateTime column and go to properties and change StoreGeneratedPattern from None to Computed.
This worked perfectly! However, we are going with the db-first approach so is there any way EF would scaffold the models with this annotation? The reason I ask is because there are a lot of tables and each have a ModifiedDate and SysModifiedUser field.
@toadfromgrove Guessing you're using EF6 where default constraints aren't persisted? You could create partial classes for your entities that sets the property as a workaround.
@ChrisPickford Yes, I just checked and it's EF 6.1.3. In NuGet it shows 6.1.3 as the latest stable version. Is there a newer version that does take constraints into account when scaffolding?
I believe EF7 will do, but don't quote me on that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.