Avi Levin
Avi Levin

Reputation: 1868

Pull on insert the auto increment id

I'm using a SQL Server (.MDF) database with C# and I want pull on insert the auto increment id.

Currently I have a table with 3 cells:

  1. Id || int
  2. StartDate || datetime
  3. GameMode || nchar(10)

On code level I'm not inserting the ID cell, the setup of the database takes care of it:

db.TblGames.InsertOnSubmit(new TblGame { StartDate = DateTime.Now, GameMode = gm.ToString() });
db.SubmitChanges();

Any ideas?

Upvotes: 0

Views: 173

Answers (1)

cynic
cynic

Reputation: 5405

I take it you're using LINQ to SQL. The auto-generated id should be in the TblGame instance after .SubmitChanges() returns. Keep the TblGame instance to retrieve it, like this:

var game = new TblGame { StartDate = DateTime.Now, GameMode = gm.ToString() };
db.TblGames.InsertOnSubmit(game);
db.SubmitChanges();
var id = game.Id;

Upvotes: 1

Related Questions