简体   繁体   中英

How can I retrieve Id of inserted entity using Entity framework?

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?

According to Entity Framework the solution is:

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

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

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.

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
}

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

I had been using Ladislav Mrnka's answer to successfully retrieve Ids when using the Entity Framework however I am posting here because I had been miss-using it (ie using it where it wasn't required) and thought I would post my findings here in-case people are looking to "solve" the problem I had.

Consider an Order object that has foreign key relationship with Customer. When I added a new customer and a new order at the same time I was doing something like this;

var customer = new Customer(); //no Id yet;
var order = new Order(); //requires Customer.Id to link it to customer;
context.Customers.Add(customer);
context.SaveChanges();//this generates the Id for customer
order.CustomerId = customer.Id;//finally I can set the Id

However in my case this was not required because I had a foreign key relationship between customer.Id and order.CustomerId

All I had to do was this;

var customer = new Customer(); //no Id yet;
var order = new Order{Customer = customer}; 
context.Orders.Add(order);
context.SaveChanges();//adds customer.Id to customer and the correct CustomerId to order

Now when I save the changes the id that is generated for customer is also added to order. I've no need for the additional steps

I'm aware this doesn't answer the original question but thought it might help developers who are new to EF from over-using the top-voted answer for something that may not be required.

This also means that updates complete in a single transaction, potentially avoiding orphin data (either all updates complete, or none do).

You need to reload the entity after saving changes. Because it has been altered by a database trigger which cannot be tracked by EF. SO we need to reload the entity again from the DB,

db.Entry(MyNewObject).GetDatabaseValues();

Then

int id = myNewObject.Id;

Look at @jayantha answer in below question:

How can I get Id of the inserted entity in Entity framework when using defaultValue?

Looking @christian answer in below question may help too:

Entity Framework Refresh context?

You have to set the property of StoreGeneratedPattern to identity and then try your own code.

Or else you can also use this.

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

  int id = myNewObject.Id; // Your Identity column ID
}

在将更改传播到数据库后,您保存的对象应该具有正确的Id

I come across a situation where i need to insert the data in the database & simultaneously require the primary id using entity framework. Solution :

long id;
IGenericQueryRepository<myentityclass, Entityname> InfoBase = null;
try
 {
    InfoBase = new GenericQueryRepository<myentityclass, Entityname>();
    InfoBase.Add(generalinfo);
    InfoBase.Context.SaveChanges();
    id = entityclassobj.ID;
    return id;
 }

您只能在保存后获取 ID,而在保存之前您可以创建一个新的 Guid 并分配。

All answers are very well suited for their own scenarios, what i did different is that i assigned the int PK directly from object (TEntity) that Add() returned to an int variable like this;

using (Entities entities = new Entities())
{
      int employeeId = entities.Employee.Add(new Employee
                        {
                            EmployeeName = employeeComplexModel.EmployeeName,
                            EmployeeCreatedDate = DateTime.Now,
                            EmployeeUpdatedDate = DateTime.Now,
                            EmployeeStatus = true
                        }).EmployeeId;

      //...use id for other work
}

so instead of creating an entire new object, you just take what you want :)

EDIT For Mr. @GertArnold :

在此处输入图片说明

There are two strategies:

  1. Use Database-generated ID ( int or GUID )

    Cons:

    You should perform SaveChanges() to get the ID for just saved entities.

    Pros:

    Can use int identity.

  2. Use client generated ID - GUID only.

    Pros: Minification of SaveChanges operations. Able to insert a big graph of new objects per one operation.

    Cons:

    Allowed only for GUID

Repository.addorupdate(entity, entity.id);
Repository.savechanges();
Var id = entity.id;

This will work.

When you use EF 6.x code first

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

and initialize a database table, it will put a

(newsequentialid())

inside the table properties under the header Default Value or Binding, allowing the ID to be populated as it is inserted.

The problem is if you create a table and add the

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

part later, future update-databases won't add back the (newsequentialid())

To fix the proper way is to wipe migration, delete database and re-migrate... or you can just add (newsequentialid()) into the table designer.

I am using MySQL DB & I have an AUTO_INCREMENT field Id .

I was facing the same issue with EF.

I tried below lines, but it was always returning 0.

      await _dbContext.Order_Master.AddAsync(placeOrderModel.orderMaster);
      await _dbContext.SaveChangesAsync();

      int _orderID = (int)placeOrderModel.orderMaster.Id;

在此处输入图像描述 But I realized my mistake and corrected it.

The Mistake I was doing: I was passing 0 in my orderMaster model for Id field

在此处输入图像描述

Solution worked: Once I removed the Id field from my orderMaster model, It started working.

在此处输入图像描述

I know it was very silly mistake, but just putting here if anyone is missing this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM