如何使用实体框架检索插入实体的 ID? [英] How can I retrieve Id of inserted entity using Entity framework?

查看:32
本文介绍了如何使用实体框架检索插入实体的 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ASP.NET 中遇到实体框架问题.每当我向数据库添加对象时,我都想获取 Id 值.我该怎么做?

I have a problem with Entity Framework in ASP.NET. I want to get the Id value whenever I add an object to database. How can I do this?

根据实体框架,解决方案是:

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

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

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

This doesn't get the database table identity, but gets the assigned ID of the entity, if we delete a record from the table the seed identity will not match the entity ID.

推荐答案

这很容易.如果您使用 DB 生成的 ID(如 MS SQL 中的 IDENTITY),您只需将实体添加到相关 上的 ObjectSetSaveChanges对象上下文.Id 将自动为您填写:

It is pretty easy. If you are using DB generated Ids (like IDENTITY in MS SQL) you just need to add entity to ObjectSet and SaveChanges on related ObjectContext. Id will be automatically filled for you:

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

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

当使用自动生成的 Id 时,实体框架默认跟随每个 INSERTSELECT SCOPE_IDENTITY().

Entity framework by default follows each INSERT with SELECT SCOPE_IDENTITY() when auto-generated Ids are used.

这篇关于如何使用实体框架检索插入实体的 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆