Inserting New Data

To insert a row into the database

  1. Create a new object that includes the column data to be submitted.
  2. Add the new object to the LINQ to SQL Table collection associated with the target table in the database.
  3. Submit the change to the database.

What earlier was adding rows to tables, now is just adding new objects to context collections. When you are ready to send the changes to the database, call SubmitChanges() method of the context. Before doing this, you must first set all properties that do not support null (Nothing) values. The SubmitChanges() method generates and executes commands that perform the equivalent INSERT, UPDATE, or DELETE statements against the data source.

CrmDemoDataContext context = new CrmDemoDataContext();

// Create a new category
ProductCategory newCategory = new ProductCategory();
newCategory.CategoryID = 1000;
newCategory.CategoryName = “New category”;

// Create a new product
Product newProduct = new Product();
newProduct.ProductID = 2000;
newProduct.ProductName = “New product”;
newProduct.Price = 20;

// Associate the new product with the new category
newProduct.ProductCategory = newCategory;
context.Products.InsertOnSubmit(newProduct);

// Send the changes to the database.
// Until you do it, the changes are cached on the client side.
context.SubmitChanges();

// Request the new product from the database
var query = from it in context.Products
where it.ProductID == 2000
select it;

// Since we query for a single object instead of a collection, we can use the method First()
Product product = query.First();
Console.WriteLine(”{0} | {1} | {2}”,
product.ProductCategory.CategoryName, product.ProductName, product.Price);
Console.ReadLine();

The InsertOnSubmit() method is created for every collection in the context. This method stores in the database information about all linked objects. As shown in the example, it is only necessary to call InsertOnSubmit() once to submit both product and category objects.

Note that after you have added the new product and category by submitting the changes, you cannot execute this solution again as is. To execute the solution again, change the IDs of the objects to be added.

Leave a Reply

You must be logged in to post a comment.