Vick
Vick

Reputation: 33

Unable to update Nullable field with Null

Facing a strange problem with EF at the moment. I have a table in database with nvarchar(MAX) data type and is a nullable field. While updating the entries in the table when I assign null to this field its not saving that null, rather keeping the old value intact. But saving the empty string in it works. My code looks like this,

myobject.field1 = null; // assigning **null** here.
dbcontext.update();
dbcontext.saveChanges();

Any solution or guidance will be really appreciated.

What I have tried:

UseCSharpNullComparisonBehavior 

and

UseDatabaseNullSemantics

EDIT:

Found the culprit, Our application has Unit of Work and Repositories implemented and we have a base Repository which includes a update method like below,

public virtual void Update(T entity)
        {

            //Ensure only modified fields are updated.
            _dbEntities.Set<T>().Attach(entity);
            var dbEntityEntry = _dbEntities.Entry<T>(entity);
            foreach (var property in dbEntityEntry.OriginalValues.PropertyNames)
            {               
                var current = dbEntityEntry.CurrentValues.GetValue<object>(property);
                if (current != null)
                    dbEntityEntry.Property(property).IsModified = true;
            }   

        }

In this function, updation is restricted in the null case. Though In my opinion this logic is invalid as it does not let the user change the existing value to null if user wants to.

Would love to hear the expert's opinion on this.

Sorry to bother you all.I am new to this kind of advanced logics and that make me stuck.

Upvotes: 0

Views: 2243

Answers (1)

bruno.almeida
bruno.almeida

Reputation: 2896

Try do this:

myobject.field1 = null;
dbcontext.Entry(myobject).Property(x => x.field1).IsModified = true;
dbcontext.saveChanges()

Upvotes: 2

Related Questions