views:

410

answers:

3

When creating a new object that is mapped to one of my SQL Server tables, LINQ inserts a new record into the table when I call SubmitChanges. I want to prevent this, but still need my new object.

I know about the custom methods, but is there anyway to disable this behaviour so that it just updates existing records and never inserts new records, regardless of if I've called MyTableClass myObject = new MyTableClass() or not.

Thanks.

A: 

Can you not prevent it at the server side? Connect as a role which doesn't have insert access. Sooner or later, that's going to be the most bulletproof way of presenting inserts, I suspect.

Jon Skeet
We use windows auth, so using one app they can insert, but other apps they shouldn't, for example.
HAdes
+1  A: 

You could always create a stored procedure which doesn't do anything and allocate that to the insert role - it's a real hack but it'll get the job done!

I would suggest that perhaps the fact that this issue is coming up indicates that there's something wrong with the approach you're taking in referencing this object - what precisely necessitates the use of this new object?

kronoz
+1  A: 

If you want your data-context to barf at inserts, you can do:

partial class DataClasses1DataContext
{
    public override void SubmitChanges(System.Data.Linq.ConflictMode failureMode)
    {
        if(GetChangeSet().Inserts.OfType<MyObject>().Any())
        {
            throw new InvalidOperationException("No inserts!");
        }
        base.SubmitChanges(failureMode);
    }
}

Any good?

[was: Could you simply add it as "clean" - i.e. Attach(obj, false);

If you don't want the object in the model, why add it to the data context?]

Marc Gravell
Because I still need to be able to retrieve the data and update the data, just not insert.
HAdes
Thanks. It's not all inserts i want to prevent though, just one table. I will give your Attach(obj, false) a go, but will have to pass the datacontext around all my objects, which i don't like.
HAdes
Can you clarify: is this a child on a new/existing record?
Marc Gravell
Updated for single type...
Marc Gravell