【问题标题】:How to get the Identity value from C# object initializer [duplicate]如何从 C# 对象初始化程序中获取标识值 [重复]
【发布时间】:2014-09-27 22:08:23
【问题描述】:

我正在使用对象初始化器将数据插入到使用实体框架的表中。数据完美地保存到数据库中,但我想从该表中检索身份。

这是我的代码:-

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();

但我不知道如何从该表中检索身份??

【问题讨论】:

    标签: c# entity-framework


    【解决方案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;
    

    【讨论】:

    • 我没有最低点来支持你。不过谢谢
    【解决方案2】:

    您应该执行以下操作:

    var cmsQueue = new CMSQUEUE { ... };
    db.CMSQUEs.Add(cmsQueue);
    db.SaveChanges();
    
    // Get the id from the object.
    var id = cmsQueue.Id;
    

    Entity Framework 确保在您插入的对象上设置了标识属性。所以这只是重新排列一些代码的问题。

    【讨论】:

      猜你喜欢
      • 2013-07-23
      • 2016-10-20
      • 2016-02-09
      • 2015-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-13
      • 1970-01-01
      相关资源
      最近更新 更多