locked
Set default value on property in Entity Framework 6.1.3 RRS feed

  • Question

  • User-2133486755 posted

    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. In constructor I have tried false value, field still doesn't have default value. 

    The solution presented below, also didn't succeed.

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

    Tuesday, January 30, 2018 7:33 PM

Answers

All replies

  • User475983607 posted

    The default value of a bool type is false.

    public bool IsDeleted { get; set; }

    Are you trying to set a DEFAULT constraint in SQL?  Can you explain the problem you are trying to solve?

    You can use a MetaData class and set a default that way.

    https://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute(v=vs.110).aspx

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 30, 2018 8:57 PM
  • User1120430333 posted

    The easiest thing to do is set the default value in code when you do something with the object, like up at the UI. You know what the state of the object is supposed to be at the time it is being used in code where code is populating the object.

    You know when you Get the User object, it exist in the database, that you need to set IsDelete to false. You know that if you instance User as new because you know you are going to add a new User, then IsDelete is false. You know in code when User is to be deleted and set IsDelete = true,

    Tuesday, January 30, 2018 9:08 PM