2

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.

1
  • The "new" by itself won't do anything... you'd need to go out of your way to add it (Attach/InsertOnSubmit) to the context...? Commented Oct 14, 2008 at 11:48

3 Answers 3

3

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?]

Sign up to request clarification or add additional context in comments.

3 Comments

Because I still need to be able to retrieve the data and update the data, just not insert.
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.
Can you clarify: is this a child on a new/existing record?
2

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?

Comments

1

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 preventing inserts, I suspect.

1 Comment

We use windows auth, so using one app they can insert, but other apps they shouldn't, for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.