Existing entity is marked as dirty when a field's value is set to null even if its CurrentValue was null

Posts   
 
    
Kazak1
User
Posts: 39
Joined: 30-May-2006
# Posted on: 05-Oct-2006 00:38:57   

I noticed that for an entity that is not new (IsNew == false), when I set a field's value to null, the entity is marked as dirty even if its CurrentValue was already null.

What's the reason for this behaviour?

Walaa avatar
Walaa
Support Team
Posts: 14950
Joined: 21-Aug-2005
# Posted on: 05-Oct-2006 08:30:19   

The Field value has to be updated in the following situations: - when the entity is new and: - the field hasn't been changed - the field has been changed but the value is different, only if the current value is not null - when the entity is not new and: - the field is already changed - the field's DbValue is null and value is not null - the field's DbValue is not null and the field's CurrentValue is different than the new value and not null - the field's CurrentValue is null

Don't set the field to any value if you want it to stay unchanged and for the entity to stay clean.

Also please refer to the following thread for some relevant explanation: http://www.llblgen.com/tinyforum/Messages.aspx?ThreadID=7696

Kazak1
User
Posts: 39
Joined: 30-May-2006
# Posted on: 05-Oct-2006 19:01:43   

Why do null values get a special treatment? Shouldn't they be trated as just values?

[Test]
public void IsDirtyNotSetWhenValuesAreNull()
{
    TestEntity entity = new TestManager().GetTestByID(306582);

    Assert.IsTrue(!entity.IsNew);
    Assert.IsTrue(!entity.IsDirty);
    Assert.IsNull(entity.Field1);

    entity.Field1 = null;
    Assert.IsTrue(!entity.IsDirty); // fails
}

[Test]
public void IsDirtyNotSetWhenValuesAreSame()
{
    string someValue = "321";

    TestEntity entity = new TestManager().GetTestByID(309989);

    Assert.IsTrue(!entity.IsNew);
    Assert.IsTrue(!entity.IsDirty);
    Assert.AreEqual(entity.Field1, someValue);

    entity.Field1 = someValue;
    Assert.IsTrue(!entity.IsDirty); // passes
}

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39614
Joined: 17-Aug-2003
# Posted on: 05-Oct-2006 23:16:03   

Because the start value of CurrentValue is null, and that means it's NOT set to a value. You can switch IsNew to false at any moment, so it can't 'assume' a new entity at time T is also saved as a new entity at time T+t. You could use it to update entities directly in the DB. You then need this check.

Frans Bouma | Lead developer LLBLGen Pro