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

和自甴很熟 提交于 2019-12-25 17:05:45

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/35417379/how-to-override-sql-server-default-value-constraint-on-a-boolean-when-inserting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!