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
Leave a Reply Cancel reply
Top Posts
- LINQ To SQL Tutorial
- LINQ To SQL Join On Multiple Conditions
- Code Sample: Programmatically Download File Using C#
- Windows 7 Control Panel In Classic Mode
- More Details Emerge On Microsoft Master Certification
- Use SqlConnection With LINQ To SQL
- Free Icons And Images With Visual Studio 2008
- Capture XML In WCF Service
- Dynamic Sort With LINQ
- StyleCop Tutorial
Tags
.Net 2010 ADO.NET ASP.NET Azure Blogging Books Browsers C# Certification Cloud Computing Code Snippets Community Data Services Eclipse Entity Framework Google IDE Java LINQ Mac Microsoft Museum NetBeans Office Oracle REST SharePoint Silverlight SQL Server T-SQL Tips Tools Training Visual Studio Visual Studio 2010 WCF Web Windows Windows 7 Windows Forms Windows Live WMI WPF XAML


[...] Insert Master Detail Data with LINQ to SQL and Select Max Value with LINQ to SQL (Deepak Kapoor) [...]
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.
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.
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.
Thank you Very Helpful
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,
I think your code expects PK column in your table to be identity.
Hi
Thank you for your comment. But what’s your solution for editing items ?