|
Insert Master Detail Data With LINQ To SQL
Best thing about running One .Net Way is interaction with members of developer community. I thoroughly enjoy answering questions which come my way through this site. Early in the morning today I saw a question by Joey. To avoid loosing details in paraphrasing, here is the exact question asked by Joey.
I’m new to LINQ. If I had two tables “Customer” and “CustomerDetails”, how (using LINQ) can I insert to both of these tables? Do I need to create a “Customer” object as well as a “CustomerDetails” object?
In short the answer is yes. LINQ can insert to both tables, you will need to populate both Customer and CustomerDetails objects with data. I will now present an example to support my answer.
What we have here is a one to many scenario which involves two tables linked through a Foreign Key. To serve as an example, I have modelled the tables like this.
Each customer can have many nick names which are stored in CustomerDetails table. Let’s go ahead and generate LINQ To SQL entities. Please refer to LINQ To SQL tutorial if you want a refresher on how to generate LINQ To SQL entities. After dragging our tables to designer we can see that designer has recognised relationship we have between our tables.
A quick glance over generated code confirms that we have a property of Type EntitySet<CustomerDetails> in our Customer class.
Now let’s insert some data. The following code will insert one Customer record and two CustomerDetails records.
private void InsertData() { string firstName = "LINQ"; string lastName = "Dude"; string nickName1 = "Cool"; string nickName2 = "DataBuster"; using (CustomerDatabaseDataContext context = new CustomerDatabaseDataContext()) { // Create a Customer object Customer customer = new Customer { FirstName = firstName, LastName = lastName, // Create two CustomerDetails objects CustomerDetails = new System.Data.Linq.EntitySet<CustomerDetail>() { new CustomerDetail{NickName = nickName1}, new CustomerDetail{NickName = nickName2} } }; // We'd like to Insert our changes as new context.Customers.InsertOnSubmit(customer); // Submit changes to database context.SubmitChanges(); } }
Code above produces following T-SQL
exec sp_executesql N'INSERT INTO [dbo].[Customer]([FirstName], [LastName]) VALUES (@p0, @p1) SELECT CONVERT(Int,SCOPE_IDENTITY()) AS [value]',N'@p0 varchar(4),@p1 varchar(4)', @p0='LINQ',@p1='Dude' go exec sp_executesql N'INSERT INTO [dbo].[CustomerDetails]([CustomerId], [NickName]) VALUES (@p0, @p1) SELECT CONVERT(Int,SCOPE_IDENTITY()) AS [value]',N'@p0 int,@p1 varchar(4)', @p0=2,@p1='Cool' go exec sp_executesql N'INSERT INTO [dbo].[CustomerDetails]([CustomerId], [NickName]) VALUES (@p0, @p1) SELECT CONVERT(Int,SCOPE_IDENTITY()) AS [value]',N'@p0 int,@p1 varchar(10)', @p0=2,@p1='DataBuster' go
In T-SQL above you can see that we are inserting one row for Customer and two rows for CustomerDetails. However in our C# we only called SubmitChanges once.
8 Responses to “Insert Master Detail Data With LINQ To SQL”
Trackbacks
- Dew Drop – July 8, 2009 | Alvin Ashcraft's Morning Dew July 9th, 2009
Leave a Reply
Get Updates By Email
Popular Post
- LINQ To SQL Tutorial
- LINQ To SQL Join On Multiple Conditions
- Code Sample: Programmatically Download File Using C#
- Free Icons And Images With Visual Studio 2008
- Windows 7 Control Panel In Classic Mode
- Dynamic Sort With LINQ
- Use SqlConnection With LINQ To SQL
- StyleCop Tutorial
- Write To Vista Event Log Using C#
- More Details Emerge On Microsoft Master Certification
Tag Cloud
Code Snippets
- Get Current Windows User In C#
- Get Width And Height Of Image In C#
- Get Windows Registry Size With WMI And C#
- Reverse Array Elements Using C#
- Convert Hexadecimal To Number In C#
- Get Free Disk Space Using T-SQL
- SQL Server 2008 – Get All Indexes In A Database
- Get Name Of Current Executing Assembly In C#
- Get CD Or DVD Drive Information Using WMI And C#
- Get Last Row From Table Using LINQ To SQL


September 26th, 2009 at 2:20 am
Any ideas how to insert an arbitrary number of CustomerDetail objects to that entity set via a nested LINQ expression? I’m trying to read XML document via Linq-to-XML and generate a Linq-to-SQL entity in one shot, but I can’t figure out the syntax/if it’s possible.
December 11th, 2009 at 7:01 am
Hi.
I’m totally newbie with LINQ. I want to know how to display the row that we just added with the code (the last row on the table).
Thanks.
December 11th, 2009 at 8:34 am
Hi Graciela,
You DataContext already has the row that you inserted. As you are doing this from C#/VB.NET code you already know what you are inserting.
I hope I understood your question. If not then can you please post an example and I’ll be able to help you.
January 28th, 2010 at 4:37 pm
Thank you Very Helpful
February 14th, 2010 at 3:19 am
I have created the database and copy/pasted the code (just changed the name of the context) the rest is unchanged and I’m getting error:
DuplicateKeyException was unhandled
Message=Cannot add an entity with a key that is already in use.
Source=System.Data.Linq
Any idea what might be the problem?
Thanks in advance.
John,
February 15th, 2010 at 6:17 pm
I think your code expects PK column in your table to be identity.
February 17th, 2010 at 6:28 pm
Hi
Thank you for your comment. But what’s your solution for editing items ?