Linq-to-SQL-Insert-syntex

Linq-to-SQL-Insert-syntex


Referring to http://www.revenmerchantservices.com/page/Linq-to-Sql.aspx

Insert new Item into DB using Linq to SQl

First we will add Locations in to .DBML file. Drag and drop the Locations table into .DBML file

and perform below action to insert new location and show it on grid.

AdventureWorksDataContext dbc = new AdventureWorksDataContext();    // Create an object of Database context

Location locationinfo = new Location();   // Create entity of Location

locationinfo.Name = "Pune";    // Populate entity with Names,and other field

locationinfo.Availability = 1.5M;

locationinfo.CostRate = 1.6M;

locationinfo.ModifiedDate = DateTime.Now;

dbc.Locations.InsertOnSubmit(locationinfo);    // Pass this location entity to Database context for insertation

dbc.SubmitChanges();     // update changes into SQL

var query = from locationEntity in dbc.Locations     // Query the locations table for newly inserted field locations

where locationEntity.Name == "Pune"

select locationEntity;

GridView1.DataSource = query;     // Bind the query to Grid

GridView1.DataBind();

- Satalaj

 

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.