tags:

views:

613

answers:

3

hi, i need to insert two table object in single query is it possible to do in linq. At present i am using insertonsubmit() 2 times.

+1  A: 

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.

Marc Gravell
"This will still result in to " should probably read "This will still result in two"
Winston Smith
@Joe - thanks. My stoopid fingers!
Marc Gravell
+2  A: 

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

Lauri Larjo
what is db, db is databasecontext obj or any other object
vineth
A: 

what is db . db is databasecontext or any other table object ,pls explain the db

i am not getting the add() //and finally db.Categories.Add(c);

vineth
Looks like confusion between LINQ 2 SQL and LINQ to Entities (Entity Framework) syntax
RobS
A good comparison of differences between EF and L2S: http://stackoverflow.com/questions/589906/how-to-move-from-linq-2-sql-to-linq-2-entities
RobS