Reputation: 17033
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.
Upvotes: 2
Views: 829
Reputation: 1503749
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.
Upvotes: 1
Reputation: 1064184
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?]
Upvotes: 3
Reputation: 37847
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?
Upvotes: 2