in

System.Data.SQLite

An open source ADO.NET provider for the SQLite database engine

How to acquire the ID of last row inserted using Entity Framework?

Last post 09-30-2008 8:47 AM by SqlRanger. 1 replies.
Page 1 of 1 (2 items)
Sort Posts: Previous Next
  • 09-30-2008 5:48 AM

    How to acquire the ID of last row inserted using Entity Framework?

     Hi there,

    Does anyone happen to know if there is a way in the Entity Framework to return me the ID of a just inserted row, assume the column is an integer type and is Identity column?  This feature should be similar to scope_identity() in T-SQL, or last_rows_affected() for Sqlite.  But since I'm not using sprocs, so I'm just wondering if there is a way to do this just within my C# code with linq to EF?  Maybe call on some functions or something, does anyone know?

    Thank you so much,

    Ray.
  • 09-30-2008 8:47 AM In reply to

    Re: How to acquire the ID of last row inserted using Entity Framework?

    Identity columns get its value after the entity is saved.

    Given the following table:

    CREATE TABLE T2 ( ID INTEGER PRIMARY KEY AUTOINCREMENT, Value TEXT)

    The following code shows you the id for the inserted row:

    using (TestEntities entities = new TestEntities())
    {
        T2 t2 = new T2();
        t2.Value = "some value";
        entities.AddToT2(t2);
        entities.SaveChanges();
    
        Console.WriteLine(t2.ID);
    
    }
    

     

     

     

     

    Regards

    Jesús López

Page 1 of 1 (2 items)
Powered by Community Server (Commercial Edition), by Telligent Systems