How can I get Id of inserted entity in Entity fram

2018-12-31 20:01发布

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?

11条回答
人间绝色
2楼-- · 2018-12-31 20:06

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.AddObject(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 Ids are used.

查看更多
何处买醉
3楼-- · 2018-12-31 20:06

You can get ID only after saving, instead you can create a new Guid and assign before saving.

查看更多
听够珍惜
4楼-- · 2018-12-31 20:12

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 (i.e. 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.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.

查看更多
千与千寻千般痛.
5楼-- · 2018-12-31 20:18

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;
 }
查看更多
几人难应
6楼-- · 2018-12-31 20:19

Please refer this link.

http://www.ladislavmrnka.com/2011/03/the-bug-in-storegeneratedpattern-fixed-in-vs-2010-sp1/

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
}
查看更多
临风纵饮
7楼-- · 2018-12-31 20:26

You need to reload the entity after savechanges. 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 inserted entity in Entity framework when using defaultValue?

Looking @christian answer in below question may help too:

Entity Framework Refresh context?

查看更多
登录 后发表回答