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.
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.
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
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);