首页 文章

如何在Entity框架中获取没有saveChanges的插入实体的Id? [重复]

提问于
浏览
-1

这个问题在这里已有答案:

我在Asp.net中遇到了Entity Framework的问题 . 每当我将对象添加到数据库而不执行SaveChanges()时,我想获取Id值 . 我怎样才能做到这一点?

2 回答

  • 0

    如果使用序列生成键值而不是IDENTITY列,则可以在插入数据库之前获取键值 .

    EF Core支持本机Sequences,您可以使用一些自定义SQL在EF6中执行此操作 .

  • 2
    //MyClass has Id as property, this is set by the DB server
    var myObject = new MyClass { NotIdProp = someVal; }
    
    int idAfterInsert; //or string if using GUID for Id
    
    //transaction and then dispose DB context
    using (var db = new MyContext())
    {
        //add the entity object
        db.MyTable.Add(myObject);
    
       //now myObject will have its Id set by the DB server
       idAfterInsert = myObject.Id;
    
      //that's it if you don't want to Save Changes
    
    }
    

    但是,我没有看到一个模式,这可能是有用的,如果您的对象应该挂起而不是在此阶段保存,只需添加另一个SQL列,如Submitted或Approved,并使其成为 bit 值(C#中的布尔值) .

    然后在读取记录时,不要通过在bool列上过滤来获取您不想要的记录 .

相关问题