简体   繁体   中英

Getting a primary key after a LINQ2SQL insert

How can I retrieve the primary key of a newly created record by LINQ2SQL?

var peon = new Peon { name = 'Serf' };
context.Peons.InsertOnSubmit(peon);
context.SubmitChanges();

Will the LINQ2SQL model automagically get updated with the primary key? I wasn't able to find any information on this in the docs.

Or is there some other way to get the primary key of the last inserted record? Preferably without searching for the record.

The context of my question is that my class is associated to another class by many-to-many table. I need the primary key to insert the association to that table. For example:

// After previous code.
var bossPeonMapping = new { PeonId = peon.Id, BossId = boss.Id };
// Insert mapping

I'd appreciate any tips if LINQ2SQL affords me a better way to do this.

After you submit changes the entity should have it's primary key value.

In the Linq2SQL designer, look at the properties of the field that is the primary key. Ensure that its AutoGeneratedValue = True, and Auto-Sync = OnInsert. If they are, it should get populated with the value assigned by the database server during the insert.

Yes, the key will be available after the first submitchanges but you do not need it. You can use the entity in your new mapping. So new { Peon = peon, ... } instead of peon.id

And you can submit them both at the same time which will give you transaction management for free as well.

try
{
    var peon = new Peon { name = 'Serf' };
    context.Peons.InsertOnSubmit(peon);
    context.SubmitChanges();
    return peon.Id;
}
catch(Exception e) { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM