Friday, January 16, 2009

SubSonic versus LinqToSQL: Simple Insert

Continuing the series, here I demonstrate a simple insert using SubSonic and then the equivalent using LinqToSQL.

If you are looking for other posts in this series, here is the list:

  • SubSonic versus LinqToSQL: Simple Select

  • SubSonic versus LinqToSQL: Simple Insert

  • SubSonic versus LinqToSQL: Simple Update

  • SubSonic versus LinqToSQL: Simple Delete


  • Here is a Simple Insert using SubSonic:
    using SubSonic;
    using MyCustomDAL;

    ...

    protected void InsertProduct()
    {
    Product p = new Product();

    p.ProductName = txtProductName.Text;
    p.UnitPrice = decimal.Parse(txtUnitPrice.Text);
    p.UnitsInStock = short.Parse(txtUnitsInStock.Text);
    p.UnitsOnOrder = short.Parse(txtUnitsOnOrder.Text);
    p.QuantityPerUnit = txtQuantityPerUnit.Text;
    p.ReorderLevel = short.Parse(txtReorderLevel.Text);
    p.Discontinued = false;

    p.Save();
    }

    And here is a Simple Insert using LinqToSQL:
    using System.Linq;

    ...

    protected void InsertProduct()
    {
    NorthwindDataContext db = new NorthwindDataContext();

    Product p = new Product();
    {
    p.ProductName = txtProductName.Text;
    p.UnitPrice = decimal.Parse(txtUnitPrice.Text);
    p.UnitsInStock = short.Parse(txtUnitsInStock.Text);
    p.UnitsOnOrder = short.Parse(txtUnitsOnOrder.Text);
    p.QuantityPerUnit = txtQuantityPerUnit.Text;
    p.ReorderLevel = short.Parse(txtReorderLevel.Text);
    p.Discontinued = false;
    }
    db.SubmitChanges();

    }
    It is worth to note that between instaniating the Northwind database ("db") in the LinqToSQL and the "db.SubmitChanges();", any inserting calls that you are doing are just submitted once to the database. So, if any of them fail, they all fail.