我使用Object初始化程序使用Entity Framework将数据插入表中。数据完全保存到数据库中,但我想从该表中检索标识。
这是我的代码: -
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();
但我不知道如何从该表中检索身份?
答案 0 :(得分:1)
您需要先保留实体对象,然后在插入后重新加载它:
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;
答案 1 :(得分:1)
您应该执行以下操作:
var cmsQueue = new CMSQUEUE { ... };
db.CMSQUEs.Add(cmsQueue);
db.SaveChanges();
// Get the id from the object.
var id = cmsQueue.Id;
实体框架确保在您插入的对象上设置标识属性。所以这只是重新安排一些代码的问题。