Search code examples
c#sql-serverentity-frameworkbooleandefault-constraint

How to override SQL Server default value constraint on a boolean when inserting new entity?


This project is using Entity Framework code-first.

I have an entity called Department with a boolean value that specifies whether it is an active department. Here is a simplified version of the entity definition. There are also no fluent mappings for the Active property.

public class Department
{
    public Guid DepartmentId { get; set; }
    public string DepartmentName { get; set; }
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public bool Active { get; set; }
}

In the database the column for Active is a bit, not null.

We have a default constraint in the database for the Active column to set newly created entries to true.

ALTER TABLE [dbo].[Department] ADD  DEFAULT ((1)) FOR [Active]

The problem is that when I create a new entity the user can choose to set Active as false, but this property is false when it is added to the context, but after save changes is called, the property is true and it is true in the database record.

Guid ICommonRepository.AddDepartment(Department newDepartment)
{
    using(var db = new CommonDbContext())
    {
        if(newDepartment.DepartmentId == Guid.Empty)
        {
            newDepartment.DepartmentId = Guid.NewGuid();
        }
        db.Departments.Add(newDepartment); // Here newDepartment.Active is false
        db.SaveChanges();
        return newDepartment.DepartmentId; // Here newDepartment.Active is true
    }
}

Is there a setting in EF or an annotation that I can use on the Active column that will allow me to specify false?


Solution

  • Remove [DatabaseGenerated(DatabaseGeneratedOption.Computed)] from the Active field of your Model.

    Entity Framework will not try to persist a value to the database which is why the default is being set.