如何从c#对象初始化器中获取Identity值
本文关键字:获取 Identity 初始化 对象 | 更新日期: 2023-09-27 18:16:31
我使用对象初始化器插入数据到表使用实体框架。数据完全保存到数据库中,但我想从表中检索身份。
下面是我的代码:-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();
但是我不知道如何从表中检索身份??
您需要首先保留实体对象,然后在插入后重新加载它:
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;
你应该这样做:
var cmsQueue = new CMSQUEUE { ... };
db.CMSQUEs.Add(cmsQueue);
db.SaveChanges();
// Get the id from the object.
var id = cmsQueue.Id;
Entity Framework确保在插入的对象上设置了identity属性。所以这只是重新排列一些代码的问题。