Get Record ID in Entity Framework after insert
This is what I'm looking for.
in partial class
protected void clientDataSource_OnInserted(object sender, EntityDataSourceChangedEventArgs e )
{
int newPrimaryKey = ((Client)e.Entity).ClientId;
Debug.WriteLine(" Client ID is " + newPrimaryKey);
}
and added below line in EntityDataSource
in aspx page.
OnInserted="clientDataSource_OnInserted"
Get Id's of recently inserted rows in Entity Framework
EntityFrameWork(EF)
after insert entity and SaveChanges()
. it sets the value of Id.
Suppose that the entity you want to enter into database is as follows:
public class EntityToInsert
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
And you want to insert a list of entity:
var list = new List<EntityToInsert>()
{
new EntityToInsert() {Name = "A", Age = 15},
new EntityToInsert() {Name = "B", Age = 25},
new EntityToInsert() {Name = "C", Age = 35}
};
foreach (var item in list)
{
context.Set<EntityToInsert>().Add(item);
}
context.SaveChanges();
// get the list of ids of the rows that are recently inserted
var listOfIds=list.Select(x => x.Id).ToList();
I hope this helps.
Entity Framework - retrieve ID before 'SaveChanges' inside a transaction
The ID is generated by the database after the row is inserted to the table. You can't ask the database what that value is going to be before the row is inserted.
You have two ways around this - the easiest would be to call SaveChanges
. Since you are inside a transaction, you can roll back in case there's a problem after you get the ID.
The second way would be not to use the database's built in IDENTITY
fields, but rather implement them yourself. This can be very useful when you have a lot of bulk insert operations, but it comes with a price - it's not trivial to implement.
EDIT: SQL Server 2012 has a built-in SEQUENCE type that can be used instead of an IDENTITY column, no need to implement it yourself.
Related Topics
Can You Overload Controller Methods in ASP.NET MVC
How to Make Calls to a Rest API Using C#
Data Binding to Selecteditem in a Wpf Treeview
Filtering Datagridview Without Changing Datasource
Splash Screen Waiting Until Thread Finishes
How to Get Output from a Command to Appear in a Control on a Form in Real-Time
What's the Main Difference Between Int.Parse() and Convert.Toint32
Redirecttoaction With Parameter
Creating a Dpi-Aware Application
Creating Wizards For Windows Forms in C#
Dpi Awareness - Unaware in One Release, System Aware in the Other
Entity Framework 5 Updating a Record
Killing Gracefully a .Net Core Daemon Running on Linux
How to Extract Text That Lies Between Parentheses (Round Brackets)