How to get the identifier of an object after calling SaveChanges (), when the object is mapped to stored procedures

We use Entity Framework 4.0, and we have an object that maps to stored procedures provided by our database administrator. The Insert, Update, and Delete functions in the mapping data have their own stored procedures.

When using objects mapped to tables, I can add a new object, call dataContext.SaveChanges();, and then a new instance that I created automatically has an ID property populated with the value from the identification column in the database.

How can this be done when an object is mapped to stored procedures? Does the INSERT stored procedure store anything special and / or do I need to do something special on dataContext.SaveChanges();?

Example

Traditional way

var newCustomer = new Customer
{
    Name = "Fred",
    Age = 24
};

// newCustomer.Id is null

dataContext.Customers.Add(newCustomer);
dataContext.SaveChanges()

// newCustomer.Id is what database identity column was set to.

Mapped to stored procedures.

var newCustomer = new Customer
{
    Name = "Fred",
    Age = 24
};

// newCustomer.Id is null

dataContext.Customers.Add(newCustomer);
dataContext.SaveChanges()

// newCustomer.Id is null
+5
source share
2 answers

If you are using the Identity column in a database, make sure your stored procedure contains:

SELECT Scope_Identity() AS Id

after calling INSERT

Also make sure that PK in your entity mode is correctly configured with StoreGeneratedPatternset to Identity(should be automatic if you used update from the database)

+9
source

, @@identity NewID() Identity/NewID . , ; , ( SP .Net), , , . , .

:

PK, , , from e in context.entities where e.pkcolumn = spkeyreturned select e.

, , , Attach. , . Entity.

+1

All Articles