tags:

views:

9

answers:

0

I'm trying to achieve something similar to what's described in this old SO post, which never got a proper answer. I'm trying to find a way to delegate setting the primary key of newly inserted objects to the DataContext InsertX() partial methods when SubmitChanges() is called. Essentially, this makes primary key generation lazy, and better separates it from the business logic.

public class Foo
{
    public int Id
    {
        get ...
        set ... // usual linq to sql bodies
    }
}
...
// provide an implementation for the insert overload
public class DB : DataContext
{
    partial void InsertFoo(Foo instance)
    {
        instance.Id = GetNextFooId();
        ExecuteDynamicInsert(instance);
    }
}

This currently fails when inserting more than one object with a DuplicateKeyException, possibly because LINQ to SQL tries to access the primary keys to distinguish instances from each other? I've tried overriding the Equals and GetHashCode to solve this problem, but no dice.

The exception provides no details as to which specific class is causing the problem, and there's no way to log the internal operation of the DataContext, so I'd appreciate any suggestions!

If there's some sort of pre-update event that fires at some point, I could hook into that, but the DataContext Insert overload is the only way I could see. Perhaps LINQ to SQL simply can't express this pattern, as it would need an InsertingFoo/InsertedFoo distinction to mirror the PropertyChanging/PropertyChanged.