user1108948
user1108948

Reputation:

To get identity value in Entity Framework 6

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?

Upvotes: 3

Views: 4328

Answers (4)

Callum Linington
Callum Linington

Reputation: 14417

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;
            }

Upvotes: 9

Palak Bhansali
Palak Bhansali

Reputation: 731

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.

Upvotes: 0

AKD
AKD

Reputation: 3966

i think u can retrieve the TaskId while adding the Task something like :

public int AddTaskTable(int number,string[] params)
    {
        using (dbContext db = new dbContext())
        {
            var t = new Task { blah blah };
            db.Tasks.Add(t);
            try
            {
                db.SaveChanges();
                var newTaskId = dbContext
                                    .Tasks
                                    .OrderByDescending(x => x.TaskId)
                                    .FirstOrDefault().TaskId;
                return newTaskId;
             }
         }
    }

It will give u always exact value of TaskId.

Upvotes: 0

Kyle Gobel
Kyle Gobel

Reputation: 5750

The TaskId property should be filled on the entity after you save changes.

If you need it before you save changes (not the actual Id, but need to use this object as a foreign key property) you will need to use the navigational properties, and model your relationships.

Upvotes: 3

Related Questions