1

I am using Object initializer to insert data into table using Entity Framework. Data is saving into database perfectly , but i want to retrieve the Identity from that table .

Here is my code :-

db.CMSQUEs.Add(new CMSQUE
  {
    queedfcodequestiontype = questionEdfValue.ToString(),
    quenotes = model.QuestionDescription,
    queisexternaltext = false,
    quenumofoptions = model.NoofOptions,
    queusmrefidcreatedby = Convert.ToInt32(System.Web.HttpContext.Current.Session["usmrefid"]),
    quescore = model.QuestionScore / model.NoofQuestions,
    quetime = model.QuestionDuration  
  });

 db.SaveChanges();

But I don't know how to retrieve the Identity from that table ??

Electric Sheep
  • 3,867
  • 1
  • 29
  • 38
Naveen
  • 149
  • 1
  • 2
  • 13

2 Answers2

1

You need to first keep the entity object then reload it after you have inserted it:

var cmsque = new CMSQUE
{
    queedfcodequestiontype = questionEdfValue.ToString(),
    quenotes = model.QuestionDescription,
    queisexternaltext = false,
    quenumofoptions = model.NoofOptions,
    queusmrefidcreatedby = Convert.ToInt32(System.Web.HttpContext.Current.Session["usmrefid"]),
    quescore = model.QuestionScore / model.NoofQuestions,
    quetime = model.QuestionDuration  
};

db.CMSQUEs.Add(cmsque);
db.SaveChanges();
db.Entry(cmsque).GetDatabaseValues();

var identityValue = cmsque.ID;
DavidG
  • 113,891
  • 12
  • 217
  • 223
1

You should do the following:

var cmsQueue = new CMSQUEUE { ... };
db.CMSQUEs.Add(cmsQueue);
db.SaveChanges();

// Get the id from the object.
var id = cmsQueue.Id;

Entity Framework makes sure the identity property is set on the object you insert. So it's simply a matter of rearranging some code.

Ronald Wildenberg
  • 31,634
  • 14
  • 90
  • 133