none
how to get last inserted record from table? RRS feed

  • Question

  • Hi friends

    how to get last inserted record from table using linq

    please anyone help me.

    thanks in advance

    Faisal

     

     


    faisal
    Thursday, January 12, 2012 4:19 PM

Answers

  • Last inserted according to what? It could be physically last inserted or by a column value. If you are saying physically then as far as I kow in SQL server there is no guarantee that you would get the last physically inserted row. It might be the last in a select but not in the next execution of the same select. You first need to have a column that provides the "last" and order by it. It could be a timestamp column or a datetime column. Say you want to get last record by CreatedOn column which is a datetime column:

    var lastRow = (from r in db.MyTable orderby r.CreatedOn descending select r).FirstOrDefault();

    Thursday, January 12, 2012 4:52 PM

All replies

  • Last inserted according to what? It could be physically last inserted or by a column value. If you are saying physically then as far as I kow in SQL server there is no guarantee that you would get the last physically inserted row. It might be the last in a select but not in the next execution of the same select. You first need to have a column that provides the "last" and order by it. It could be a timestamp column or a datetime column. Say you want to get last record by CreatedOn column which is a datetime column:

    var lastRow = (from r in db.MyTable orderby r.CreatedOn descending select r).FirstOrDefault();

    Thursday, January 12, 2012 4:52 PM
  • Ok,

    Here is the standard behaviour if you have a pretty locked setup. But who knows, mabye you can use it.

    If you have a table, where the PK is identity. Then you drag it into the dbml, and it will have set its autosync on insert. Rightclick PK in the table, and look at properties to see it.

    Then you have a generated partial class made by the dbml file. it will default be called "DataClassesDataContext".

    Then you can make another partial class in same namespace, and here you have a method called InsertMyTable(MyTable entity)

    {

           DynamicInsert(entity);

           //Here

    }

     

    Because of some naming standards and other things, then you will go into this method on all inserts done by linq to sql.

    And the place where the "Here" comment is you will have the ID field set in the entity, because it has been autosynced.

    Friday, January 13, 2012 1:43 PM
  • Hmmm I understood the question as last inserted record (by any user) and you understood it getting the identity of what 'I inserted' - I wouldn't debate for using Guid and ending such a pain in general :)

    Friday, January 13, 2012 2:28 PM