开发者

Updating nullable boolean fields in the Entity Framework

Changes to nullable bool properties are not saved back to the db in EF4 however other fields which are nullable are updating without any issues. For example, if I execute simple query similar to the following:

EmployeeSurvey employeeSurvey = context.EmployeeSurveys.SingleOrDefault(s => s.EmployeeSurveyID == 60);

employeeSurvey.EmployeeSmokes = true; 
employeeSurvey.OtherComments = "Test comment";

context.SaveChanges();

The OtherComments changes are successfully saved back to the db however the EmployeeSmokes property changes are not. The EmployeeSmokes property is a bool? and other nullable boolean fields have the sa开发者_开发百科me issue.

Additionally, the problem only occurs when changing/updating existing EmployeeSurvery records - all properties including EmployeeSmokes are successfully saved when creating/inserting new EmployeeSurveys.

I've also tried using the ApplyCurrentValues method as per this thread but unfortunately it hasnt helped.

Any ideas why this is happening?


What is the value of employeeSurvey.EmployeeSmokes in the Database? If it is true, EF will notice there is no change and omit it från the generated Update SQL since there is no change (you can verify this in the SQL Profiler).


A few minutes after posting a comment I found a solution to my problem, that might help you too if you still need this.

I'm using self tracking entities and I had to add some code in the generated template. In the UpdateOriginalValues(ObjectContext context, IObjectWithChangeTracker entity) method I added the following fragment:

foreach(EdmProperty property in entityType.Properties)
    {
        object value;
        if(property.TypeUsage.EdmType is PrimitiveType && entity.ChangeTracker.OriginalValues.TryGetValue(property.Name, out value))
        {
            //START OF EDIT
            if (value == null && property.Nullable)
            {
                var currentValues = entry.CurrentValues;
                int ordinal = currentValues.GetOrdinal(property.Name);
                var temp = currentValues[ordinal];
                currentValues.SetDBNull(ordinal);
                entry.ApplyOriginalValues(entity);
                currentValues.SetValue(ordinal, temp);
            }
            //END OF EDIT
            originalValueRecord.SetValue(property, value);
        }
        else if(property.TypeUsage.EdmType is ComplexType)
        {
            OriginalValueRecord complexOriginalValues = originalValueRecord.GetOriginalValueRecord(property.Name);
            UpdateOriginalValues((ComplexType)property.TypeUsage.EdmType, entity.GetType().FullName, property.Name, entity.ChangeTracker.OriginalValues, complexOriginalValues);
        }
    }

The original source is HERE. I hope this will be useful!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜