tags:

views:

30

answers:

3

I mean i want to get next ID, which is identity, log it somewhere and only then do SubmitChanges()

A: 

you need to add the lastModified date column in DB and get it,if not and increment the identity column

Other wise better do SubmitChanges() and get the nextID

anishmarokey
thats the point, that i need to get new ID before submit
Dmitry
Don't forget to flag and upvote your favorite answer.
Steven
A: 

Wrap the whole thing in a transaction, do a SELECT IDENT_CURRENT('table_name') then submit your changes, the commit the transaction. If you lock the table that should prevent someone else from inserting a record after your SELECT IDENT_CURRENT and before you insert which should give you the correct identity value.

Chuck Haines
sounds good, but i need to do all in one tran, without locking(
Dmitry
A: 

Wrap the DataContext in a database transaction and call SubmitChanges to write changes to the database within that transaction. This way you can get the auto generated ID while being able to keep the operation transactional:

using (var con = new SqlConnection(conStr))
{
    con.Open();
    using (var tran = con.BeginTransaction())
    {
        using (var db = new YourDataContext(con))
        {
            // Setting the transaction is needed in .NET 3.5. It's a bug in L2S.
            db.Transaction = tran;

            var entity = new MyEntity();

            db.MyEntities.InsertOnSubmit(entity);

            db.SubmitChanges();

            var id = entity.Id;

            // Do something useful with this id
        }

        tran.Commit();
    }
}
Steven