Книга: C# 2008 Programmer
Inserting New Rows
Inserting New Rows
To insert a row into a table, use the InsertOnSubmit()
method. For example, the following code inserts a new author into the authors table:
DataClasses1DataContext database = new DataClasses1DataContext();
author a = new author() {
au_id = "789-12-3456",
au_fname = "James",
au_lname = "Bond",
phone = "987654321"
};
//---record is saved to object model---
database.authors.InsertOnSubmit(a);
Note that the InsertOnSubmit()
method only affects the object model; it does not save the changes back to the database. To save the changes back to the database, you need to use the SubmitChanges()
method:
//---send changes to database---
database.SubmitChanges();
What happens when you need to insert a new book title from a new author? As you saw earlier, the titles
table is related to the titleauthors
via the title_id
field, while the authors
table is related to the titleauthors
table via the author_id
field. Therefore, if you insert a new row into the titles table, you need to insert a new row into the authors
and titleauthors
tables as well.
To do so, you first create a new author
and title
row:
DataClasses1DataContext database = new DataClasses1DataContext();
author a = new author() {
au_id = "123-45-6789",
au_fname = "Wei-Meng",
au_lname = "Lee",
phone = "123456789"
};
title t = new title() {
title_id = "BU5555",
title1 = "How to Motivate Your Employees",
pubdate = System.DateTime.Now,
type = "business"
};
Then, add a new titleauthor
row by associating its author
and title
properties with the new title
and author
row you just created:
titleauthor ta = new titleauthor() {
author = a,
title = t
};
Finally, save the changes to the object model and submit the changes to the database:
//---record is saved to object model---
database.titleauthors.InsertOnSubmit(ta);
//---send changes to database---
database.SubmitChanges();
Notice that you do not need to worry about indicating the title_id
and author_id
fields in the titleauthors
table; LINQ to SQL does those for you automatically.
- Системные переменные ROWS_AFFECTED, GDSCODE, SQLCODE, TRANSACTIONJD, CONNECTIONJD
- State NEW packets but no SYN bit set
- 2. How to Apply These Terms to Your New Programs
- Операция new
- Browsing the Internet
- Usenet Network Newsgroups
- The Pan News Client Newsreader
- Adding New Users
- Installing the New Drive
- Mounting the New Partition and Populating It with the Relocated Files
- Usenet Newsgroups
- 13.3. cbrowser