Sunday, April 3, 2011

LINQ Query to insert data into the database.

Hi all, 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.

From stackoverflow
  • 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.

  • 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#.

    StudentDataContext db = new StudentDataContext();
    Student newStudent = new Student();
    newStudent.SName = "Billy-Bob";
    db.InsertOnSubmit(newStudent);
    db.SubmitChanges();
    
    Damien : SNo and Class will contain the default values for the database. They will be the same as if you had manually added a new row in the database.

0 comments:

Post a Comment