.NET/ASP.NET interview Questions - Using LINQ show us insert, update and delete operation..
Shivprasad Koirala
Once you have done creating the form, now you have to add LINQ to SQL Classes in your project.
Add > New item > select LINQ to SQL Classes.
As soon as you click on add a new window will appear from that just click on server explorer expand the data connection and select your database then drag and drop the table on the .dbml file like below diagram.
Now you have to add a class library file in your project.
Add > New item > select Class.
usingSystem.Data.Linq; usingSystem.Data.Linq.Mapping;namespaceLinq_to_insert {[Table(Name="Student")] publicclassClass1{ privatestring _Name; privatestring _Add;publicstring Name{ get{ _Name = value;} get{return _Name;} } publicstring Add{ set{ _Add = value; } get{return _Add;}}} }
For adding record.
protectedvoidbtnAdd_Click(object sender, EventArgs e){ DataClasses1DataContextObjDataContext = newDataClasses1DataContext(); StudentObjStud = newStudent(); ObjStud.StudentAdd = TextBox2.Text; ObjStud.StudentName = TextBox1.Text.ToString(); ObjDataContext.GetTable().InsertOnSubmit(ObjStud); ObjDataContext.SubmitChanges(); Response.Write("Record Successfully Inserted");}
protectedvoidbtnUpdate_Click(object sender, EventArgs e){ DataClasses1DataContextObjDataContext = newDataClasses1DataContext(); StudentObjStud = newStudent(); string Name1 = TextBox1.Text; string Address = TextBox2.Text; var Update = ObjDataContext.Students.Single(p =>p.StudentName == Name1); Update.StudentAdd = Address; ObjDataContext.SubmitChanges(); Response.Write("Record Successfully Updated");}
protectedvoidbtnDelete_Click(object sender, EventArgs e){ DataClasses1DataContextObjDataContext = newDataClasses1DataContext(); StudentObjStud = newStudent(); string Name1 = TextBox1.Text.ToString(); var delete = ObjDataContext.Students.Single(s =>s.StudentName == Name1); ObjDataContext.Students.DeleteOnSubmit(delete); ObjDataContext.SubmitChanges(); Response.Write("Record Successfully deleted");}
You will be also interested in watching the below video, which are also asked in most of the interviews and favourable question of interviewers.
Regards,