+92 332 4229 857 99ProjectIdeas@Gmail.com

How to add new row in table (LINQ To SQL)


How to add new row in table (LINQ To SQL)
The following code snippet shows how you can add new data row in the table and also in database. For example there is a table in your database with the name Customer, which contains the following columns in it:

ID, Name, Address
This is the connection string which let you connect to the server: 
Data Source = "Your Server Name"
Initial Catalog = "The name of your database"
Integrated Security = "true" for getting your credentials automatic to your current login account in windows, in this way you don't have to use user id and password while establishing connection with SQL server. 
public static string conString = @"Data Source =  MOAVIA_OSAMA-PC\SQLEXPRESS;Initial Catalog=MyFirst;Integrated Security=true";
The following is the class generated when you add "Linq to SQL classes" to project, which takes an argument of connection string:
DataClasses1DataContext dc = new DataClasses1DataContext(conString);
Now, you want to add a new row of data in that table, first you have to create an object of Customer class and pass values to ID, Name and Address like this:
Customer newCustomer = new Customer { ID = 6, Name = "Amal", Address = "Islamabad" };
The following statement adds the newly created Customer object to its corresponding Customers table:
dc.Customers.InsertOnSubmit(newCustomer);
The following statement saves in database table:
dc.SubmitChanges();

0 comments: