Insert, Update , Select and Delete using Linq
July 14, 2009
Hi try this example :-
NorthwindDataContext ctx = new NorthwindDataContext(); //*** Get a Single Row by ID with LINQ//Returns a single row from the database private Product GetSingleRowExample1(int productID) { Product product = (from p in ctx.Products where p.ProductID == productID select p).First(); return product; } //Returns a single row from the database (lambda) private Product GetSingleRowExample2(int productID) { return ctx.Products.Single(p => p.ProductID == productID); }//*** Get All Rows
//Retrieves all product categories private void GetAllProductCategories() { gridResult.DataSource = ctx.ProductCategories; gridResult.DataBind(); }//*** Insert a Row and Return The Generated ID
protected void btnInsertProductCategory_Click(object sender, EventArgs e) { ProductCategory productCategory = new ProductCategory(); productCategory.Name = “Sample Category”; productCategory.ModifiedDate = DateTime.Now; productCategory.rowguid = Guid.NewGuid(); int id = InsertProductCategory(productCategory); lblResult.Text = id.ToString(); } //Insert a new product category and return the generated ID (identity value) private int InsertProductCategory(ProductCategory productCategory) { ctx.ProductCategories.InsertOnSubmit(productCategory); ctx.SubmitChanges(); return productCategory.ProductCategoryID; }//*** Update a Row
The built-in change tracking in LINQ automatically determines, if connecting to the database is necessary. If an object is modified, LINQ then generates the necessary UPDATE-statemens automatically.//Retrieves and updates product category with ID of 4 protected void btnUpdateProductCategory_Click(object sender, EventArgs e) { ProductCategory productCategory =ctx.ProductCategories.Single(pc => pc.ProductCategoryID == 4); UpdateProductCategory(productCategory); } //Updates the given product category private void UpdateProductCategory(ProductCategory productCategory) { productCategory.ModifiedDate = DateTime.Now; productCategory.Name = productCategory.Name + " test"; ctx.SubmitChanges(); }//*** Delete a Row
Deleting a row is simple.
You could also remove several rows with the DeleteAllOnSubmit-method.protected void btnDeleteProductCategory_Click(object sender,EventArgs e) { ProductCategory productCategory = ctx.ProductCategories .Single(pc => pc.ProductCategoryID == 5); DeleteProductCategory(productCategory); } //Deletes the given product category private void DeleteProductCategory(ProductCategory productCategory) { ctx.ProductCategories.DeleteOnSubmit(productCategory); ctx.SubmitChanges(); }Hope this helps
Good LuckAdvertisements
Categories: Linq
Recent Comments