How can I get the following primary key for SQL 2008 in Entity Framework 4

I am using an Entity Framework 4 connection to connect to a SQL 2008 server to process the database for my application.

I use C # in Visual Studio 2010, and my question is about primary key fields that are incremented by SQL itself, is it possible at all so that I can find the identifier that will be used next to the database.

The reason that I can’t just find the last element and +1 is because if my table contains elements 1,2,3,4 and 5, deleting element 5, then adding another will cause the next element to become element 6, not 5 again (since I am using the Identity specification in SQL, but this must be used).

I can’t find any method like Item.ID.GetNextIdentity () or something like that, and looked through as many similar questions as this, but to no avail.

Any help would be appreciated

+5
source share
3 answers

There is no reliable way to use the automatic incremental identifier and display it in the form before saving. This is the wrong architecture. If you want the ID to be shown before saving the form, you must:

  • Do not use an auto-incrementing column as an identifier and handle the uniqueness of yourself
  • , ,

? , , , . // , .

, , - , .

+9

Ladislav Mrnka, , . :

        // Insert existing object in data base via EF, but PK is missing ...
        using (var Es = new MyEntities())
        {
            try
            {
                // Allows you to get next pk
                var e = new  Model.TableXXX();
                // Set pk to existing entity which has no pk
                existingEntity.PkField = e.PkField;
                // Save existing object and let garbage collector take care
                // of newly created entity
                Es.TableXXX.AddObject(existingEntity);
                Es.SaveChanges();
            }
            catch (Exception ex)
            {
                // implement exception
            }
        }
0

All Articles