save record to database using linqtosql in csharp

To save records to a database using LinqToSQL in C#, you can follow these steps:

  1. Create an instance of DataContext class by passing the connection string to the constructor.
main.cs
string connectionString = "your_connection_string";
DataContext db = new DataContext(connectionString);
104 chars
3 lines
  1. Create an instance of the table class.
main.cs
Table<YourTable> yourTable = db.GetTable<YourTable>();
55 chars
2 lines
  1. Create an object of the class whose record you want to insert.
main.cs
YourTable record = new YourTable();
record.Property1 = value1;
record.Property2 = value2;
// and so on..
105 chars
5 lines
  1. Add the object to the table's collection.
main.cs
yourTable.InsertOnSubmit(record);
34 chars
2 lines
  1. Call SubmitChanges() method of the DataContext instance to save the changes to the database.
main.cs
db.SubmitChanges();
20 chars
2 lines

gistlibby LogSnag