Isaiah Nelson
Isaiah Nelson

Reputation: 2490

How do I return the record ID on an insert transaction using Linq to SQL

I have the following LINQ to SQL insert code:

public static int InsertFileToQueue(FileInfo file)
{
    int? recordID = null; 

    IpsDBDataContext db = new IpsDBDataContext();

    IpsJobFileQueue record = new IpsJobFileQueue();
    record.FileName = file.Name;
    record.FilePath = file.FullName;
    record.PickupDate = file.CreationTime;

    record.StartTime = null;
    record.EndTime = null;
    record.ProcessCode = null;

    db.SubmitChanges();

    return recordID;
}

Somewhere after the db.SubmitChanges() I know I need to add some code to retrieve the id on the record I just inserted. The things I can't rely on are the filename (as many of these files will be named the same) and certainly not any of the times.

So what do I query for to get the ID?

Upvotes: 0

Views: 2560

Answers (1)

Enrico Campidoglio
Enrico Campidoglio

Reputation: 59923

First you should call the Table<TEntity>.InsertOnSubmit(TEntity) method passing the IpsJobFileQueue instance to persist. Then, after the DataContext.SubmitChanges() method has completed, you can retrieve the assigned primary key value from the corresponding property on the IpsJobFileQueue object.

var db = new IpsDBDataContext();
var record = new IpsJobFileQueue();
db.IpsJobFileQueues.InsertOnSubmit(record);
db.SubmitChanges();

return record.Id; // Contains the assigned primary key value

In this example IpsJobFileQueue.Id is the property that has been mapped to the primary key column of the corresponding database table.

Upvotes: 4

Related Questions