To get identity value in Entity Framework 6
c#, entity-framework
Solution
I think, when you do:
`db.SaveChanges();`
The actual model is changed, and the Id added. So if you read the model after the save it will show the updated Id that was generated.
Drawing on other answers in this chain this is very pertinent to my answer and is an explanation to my implementation:
EF creates POCO(Plain Old CLR Objects) domain models. Your entity model is not disposed, but it is in-memory. Your new task T is already in in-memory, so as soon as SaveChanges method called successfully, your object contains auto-generated ID as well.
This is my repository implementation:
public T Create<T>(T entity) where T : class
{
var newEntry = _dbContext.Set<T>().Add(entity);
_dbContext.SaveChanges();
return newEntry;
}
Here, the entity is saved, and returned back with the new Id.
In your implementation do this:
public bool AddTaskTable(int number,string[] params)
{
using (dbContext db = new dbContext())
{
var t = new Task { blah blah };
var dbTask = db.Tasks.Add(t);
try
{
db.SaveChanges();
// task id
dbTask.taskId;
return true;
}
Problem
I have an entity `Task`, its domain class is ``` public class Task { public long TaskId { get; set; } // blah blah } public DbSet<Task> Tasks { get; set; } ``` I hope that `TaskId` is the primary key and Auto-increment. Therefore we have ``` protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Task>().Property(x => x.TaskId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired(); } ``` Now I add the data to db ``` public bool AddTaskTable(int number,string[] params) { using (dbContext db = new dbContext()) { var t = new Task { blah blah }; db.Tasks.Add(t); try { db.SaveChanges(); return true; } ``` What I want to is to retrieve the `TaskId` generated by the system for future use. For example, it is a foreign key I want to use it in another entity. How to get the value?