FransBouma/LinqToSQL2

Prevent phantom inserts of empty entities

FransBouma opened this issue · 0 comments

This test fails

[Test]
public void PhantomInsertPreventionTest()
{
    var newCustomer = new Customer();
    var ba = new Address();
    var va = new Address();
    newCustomer.VisitingAddress = va;
    newCustomer.BillingAddress = ba;

    // as everything is empty, and Address isn't saved because it's not dirty, customer shouldn't be saved as well.
    using(var ctx = GetContext())
    {
        ctx.Customers.InsertOnSubmit(newCustomer);
        ctx.SubmitChanges();
        Assert.AreEqual(0, ba.AddressId);
        Assert.AreEqual(0, va.AddressId);
    }
}

because Linq to Sql happily inserts Address, while it's not dirty and has nonnullable fields. No save should occur at all, as there are only empty entities to persist. Preventing these 'phantom' inserts will avoid the user running into either empty rows (because there were nullable fields so the persist succeeded), or have to check up front whether a save is necessary.