Bharath
Bharath

Reputation:

LINQ Query to insert data into the database

In my database, I have a table named Students, with 3 Columns (SNo, SName, Class).

I want to insert the value of only SName.

Can anybody tell me how to write the LINQ Query for this.

Thanks, Bharath.

Upvotes: 6

Views: 15706

Answers (2)

Damien
Damien

Reputation: 1502

Are you using Linq-to-SQL ? Do you want to insert a new record while only specifying the Name?

If so, this is roughly how it's done in C#.

using (StudentDataContext db = new StudentDataContext())
{
    Student newStudent = new Student();
    newStudent.SName = "Billy-Bob";
    db.Students.InsertOnSubmit(newStudent);
    db.SubmitChanges();
}

Upvotes: 6

Marc Gravell
Marc Gravell

Reputation: 1062780

Do you mean you want to query only the name? In which case:

var names = ctx.Students.Select(s=>s.Name);

or in query syntax:

var names = from s in ctx.Students
            select s.Name;

To insert you'd need to create a number of Student objects - set the names but not the other properties, and add them to the context (and submit it). LINQ is a query tool (hence the Q); insertions are currently object oriented.

Upvotes: 7

Related Questions