c# - 如何使用 Entity Framework 检索插入实体的 ID?

标签 c# asp.net entity-framework

我对 ASP.NET 中的 Entity Framework 有疑问。每当我将对象添加到数据库时,我都想获取 Id 值。我该怎么做?

根据 Entity Framework解决方案是:

using (var context = new EntityContext())
{
    var customer = new Customer()
    {
        Name = "John"
    };

    context.Customers.Add(customer);
    context.SaveChanges();
        
    int id = customer.CustomerID;
}

这不会获取数据库表标识,但会获取实体的分配 ID,如果我们从表中删除一条记录,种子标识将与实体 ID 不匹配。

最佳答案

这很容易。如果您使用数据库生成的 ID(如 MS SQL 中的 IDENTITY),您只需将实体添加到 ObjectSet 和相关 上的 SaveChanges对象上下文Id 将自动为您填充:

using (var context = new MyContext())
{
  context.MyEntities.Add(myNewObject);
  context.SaveChanges();

  int id = myNewObject.Id; // Yes it's here
}

当使用自动生成的 Id 时, Entity Framework 默认跟随每个 INSERTSELECT SCOPE_IDENTITY()

关于c# - 如何使用 Entity Framework 检索插入实体的 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5212751/

相关文章:

entity-framework - 具有类似 Entity Framework 的 ORM 的通用存储库模式 + UOW 模式有什么优势

entity-framework - 当抛出 EntitySqlException 时,我可以看到正在进行的 SQL,或者我可以覆盖 EntityCommandCompilationException 吗?

c# - 确保记录具有所有关系,而不是任何关系

c# - 使用 JSON.net 将内部数组反序列化为对象

c# - 错误 : (using List class) Index was outside the bounds of array

C# - 反序列化 SOAP 消息

c# - 如何在移动设备上查看我的 ASP.net 网站

c# - 使用电子表格工具打开 protected 工作簿

asp.net - 如何使用 Angular 调用 Asp.Net Web API 2.0 http 批处理请求?

c# - 如何使用反射将 System.Type 传递给泛型方法