0

I'd like to know the equivalent LINQ-to-Entities code for the following code (which is LINQ-to-SQL):

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

In other words, I'd like to know how to insert data into an existing point in a database, using LINQ-to-Entities.

Update:

I should clarify that the table I'm inserting into is linked to two other tables with a one-to-many relationship. Is there some way to let the framework handle the updating of primary/foreign key relationships?

Update:

Found the correct answer, see How do I use LINQ-to-Entities to insert data into a specific table?

Community
  • 1
  • 1
Contango
  • 76,540
  • 58
  • 260
  • 305
  • Can you clarify on which end of the one-to-many is the table you're inserting into? Is it the "one" or the "many"? – R. Martinho Fernandes Feb 07 '11 at 17:05
  • I'm inserting into the "many". To make an insert, I'm first going to have to retrieve the primary key of the "one", then insert int the "many". I'd rather do the whole thing in LINQ, to avoid "polluting" my model with primary/foreign key relationships. – Contango Feb 07 '11 at 20:38

3 Answers3

2

The straight-up equivalent code would be something like:

StudentEntities db = new StudentEntities();
Student newStudent = new Student();
newStudent.SName = "Billy-Bob";
db.Students.AddObject(newStudent);
db.SaveChanges();

But note that you should probably be wrapping the db object with the using statement to ensure that it is properly disposed.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
  • I should clarify that the table I'm inserting into is linked to two other tables with a one-to-many relationship. Is there some way to let the framework handle the updating of primary/foreign key relationships? – Contango Feb 07 '11 at 17:01
1

My L2E has become a bit rusty, but i think there are methods generated for you on the ObjectContext, such as AddToStudents(Student), and you can use those. (call context.SaveChanges after to persist the new objects)

Botz3000
  • 39,020
  • 8
  • 103
  • 127
0

The correct answer to the question is under How do I use LINQ-to-Entities to insert data into a specific table?

Community
  • 1
  • 1
Contango
  • 76,540
  • 58
  • 260
  • 305