1

I have the following class.

public class User 
{
    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public byte[] RowVersion { get; set; }

    public bool IsDeleted { get; set; }

}

How can I set default value for property IsDeleted using Fluent API. Method HasDefaultValue is not available. I have tried to set via constructor, the same result.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
maciejka
  • 818
  • 2
  • 17
  • 42

1 Answers1

1

If you are using C#6 +, it has added the ability to assign a default value to auto-properties. So you can simply write something like this:

public bool IsDeleted { get; set; } = false;

This will set the default value to false when this column is added to your database.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • The same result. I use automatic migration. Could it be the reason? – maciejka Jan 30 '18 at 14:53
  • @maciejka What does the *The same result* is? Can you elaborate on this? – Salah Akbari Jan 30 '18 at 14:55
  • Are you using Automapper? – johnny 5 Jan 30 '18 at 15:58
  • No, I don't use. – maciejka Jan 30 '18 at 17:11
  • @S.Akbari, When I make automatic migration the columns has been created in the same way like before, when property didn;t have expression with false. – maciejka Jan 30 '18 at 17:13
  • 2
    Given the comments under the question were deleted: this code assigns a default value _to the POCO_, while the default value of a `bool` already is `false`. The OP is asking how to configure a database column to have a default value, allowing you to omit that column in an INSERT clause. That's an entirely different thing from assigning default values to POCO properties. Configuring Entity Framework Migrations to assign a default value to a database column is explained in [Entity Framework 6 Code first Default value](https://stackoverflow.com/questions/19554050/). – CodeCaster Jan 31 '18 at 09:51
  • @CodeCaster The OP has accepted the answer finally. I think you may want to change your mind about this answer and your downvote! – Salah Akbari Mar 04 '18 at 02:06
  • Nope, I still stand by my last comment. – CodeCaster Mar 04 '18 at 10:50
  • 1
    Can confirm, migration created without default value – Cute pumpkin Jan 10 '22 at 14:38
  • This answer is misleading, setting the default value on the auto properties does not affect the values passed as the `DEFAULT` if testing the migration script from `update-database`. – user692942 Feb 13 '23 at 15:33