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 ??

0

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

I don't have the minimum point to upvote you. But thanks
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.