Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL - Insert New Record

Tags:

linq-to-sql

I have a database table with an auto-incrementing ID field. this table is exposed to by code via a Entity Data Model. I am trying to write a new record to this table. I have a method that needs to be responsible for creating these records. This method takes in the property values of the record. It needs to create a record, and write a reference record in another table. Currently, here is what I am trying

public int CreateRecord(string name, string description, List<int> ids)
{
  using (DatabaseContext database = new DatabaseContext())
  {
    Record record = new Record();
    record.Name = name;
    record.Description = description;

    database.Records.InsertOnSubmit(record);
    database.SubmitChanges();

    List<RecordTrack> tracks = new List<RecordTrack>();
    foreach (int id in ids)
    {
      RecordTrack track = new RecordTrack();
      track.RecordID = record.ID;
      track.ID = id;
      tracks.Add(track);
    } 
    database.Tracks.InsertAllOnSubmit(tracks);
    database.SubmitChanges();
  }
}

I can't seem to get the record to save in this manner. I was able to do it when I passed a Record in that I wanted to insert. But due to other factors, I need a way to purely create the record here from scratch. What am I doing wrong?

Thank you!

like image 234
Villager Avatar asked May 24 '11 15:05

Villager


1 Answers

there should be a AddToRecord() function in your database context. Use that function to add your record variable and then call SaveChanges() from your database context.

like image 55
dtryan Avatar answered Oct 04 '22 16:10

dtryan