0

I need to set a default value for a field in a data model class that is part of an ASP.NET MVC Core web application I am building.

The application is being implemented with soft deletes. That is, the Model Class / DB Table has a field called "Active" it is a boolean / bit that is set to true or false accordingly. i.e. when an item is deleted then its Active value is false / 0. All items are active when created.

I know that it is possible to set the value explicitly in the controller when the data is posted to the "CreateItem" method in the controller but I'd rather not have to do that. Is there a different way? e.g. decorating the field in the Model class with an attribute.

1 Answer 1

2

I haven't tested this, but in your DBContext class you would do the following:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<YourEntity>()
            .Property(b => b.YourBooleanProperty)
            .HasDefaultValue(true);
    }

HasDefaultValue takes in an object, so I am not sure if EF does any sql mapping in this scenario so the default value you pass here could be true or 1. I would test both :-)

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

Comments

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.