Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop LINQ to SQL from executing select statements after insert

I'm using LINQ to SQL to update my database. I'm inserting a lot of records, and when I call SubmitChanges(), LINQ to SQL executes an insert and a select statement for each object. I don't really care to update my objects after they are inserted into the database.

Do you know I can prevent LINQ to SQL from issuing the select statements after the insert statements? This should make my app much faster.

like image 953
Lance Fisher Avatar asked Jan 02 '09 18:01

Lance Fisher


1 Answers

You're looking for ColumnAttribute.AutoSync. If you're using the designer, check each column for an Auto-Sync property and set it to Never.

Edit: Ok, that didn't work for you. Brace yourself for some mapping hackery!

When I Insert with some autogenerated primary key column, I get this SQL:

INSERT INTO [dbo].[TableName]( fieldlist )
VALUES (@p0, @p1, @p2, @p3, @p4)

SELECT CONVERT(Int,SCOPE_IDENTITY()) AS [value]

As I understand your request, you don't want that SELECT

Attempt 1: I went to the primary key field and set auto-generated to false. This caused a Sql Exception "Cannot insert explicit value for identity column in table 'TableName' when IDENTITY_INSERT is set to OFF." In other words, linq specified a value for that column.

Attempt 2: I deleted the autogenerated columns from the designer. This caused Linq to give me an Invalid Operation Exception: "Can't perform Create, Update or Delete operations on 'Table(TableName)' because it has no primary key."

Attempt 3: I deleted the autogenerated columns from the designer, then I marked another column as primary key. Even though this column is not a primary key in the database, LINQ's DataContext will use it to track row identity. It must be unique for observed records of a given DataContext.

This third attempt generated the following SQL (which is what you ask for)

INSERT INTO [dbo].[TableName]( fieldlist )
VALUES (@p0, @p1, @p2, @p3, @p4)
like image 85
Amy B Avatar answered Oct 12 '22 00:10

Amy B