vineth
vineth

Reputation: 883

Insert to 2 tables in single query using LINQ

I need to insert to two tables in a single query. Is this possible to do in LINQ?

At present I am using insertonsubmit() 2 times.

Upvotes: 2

Views: 4139

Answers (2)

Lauri Larjo
Lauri Larjo

Reputation: 314

If your tables have a primary key/foreign key relationship to each other, then you also have two objects which you can link to each other:

InternetStoreDataContext db = new InternetStoreDataContext(); 

Category c = new Category();
c.name = "Accessories";
Product p = new Product();
p.name = "USB Mouse";
c.Products.Add(p);

//and finally
db.Categories.Add(c);
db.SubmitChanges();

That adds your object and all linked objects when submitting the changes.

Note that for that to work, you must have a primary key in both tables. Otherwise LINQ doesn't offer you the linking possibility.

Here are good examples of using LINQ to SQL: http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062600

The database submit doesn't happen until you call SubmitChanges. There is no tangible cost associated with multiple calls to InsertOnSubmit - so why not just do that?

This will still result in two TSQL INSERT commands - it simply isn't possible to insert into two tables in a single regular INSERT command.

Upvotes: 2

Related Questions