locked
Getting Id of Newly created Object with Entity framework RRS feed

  • Question

  • User715841376 posted

    I am exposing my repositories through Unit of Work Pattern 

          public void Add(Employee emp)

         {

             context.add(emp);

         }

    UnitOfWork calls this method and then call SaveChanges method. Now i am not getting how would i get the Id of newly created employee as SaveChanges() is in UOF ?

    Thursday, June 18, 2015 9:32 AM

Answers

  • User1881638666 posted

    Hi,

    You can either change the return type of the method to 'Employee' or int.

    public int Add(Employee emp){

      context.Employees.Add(emp);

      context.SaveChanges();

      return emp.Id;

    }

    or

    public Employee Add(Employee emp){

       context.Employees.Add(emp);

       context.SaveChanges();

       return emp;

    }

    Further you can have this method in the interface for the unit of work.

    public int Add<TEntity>(TEntity entity) where TEntity : class
            {
                context.Set<TEntity>().Add(entity);
                context.SaveChanges();
                return entity.Id;
            }

    OR

     public TEntity Add<TEntity>(TEntity entity) where TEntity : class
            {
                context.Set<TEntity>().Add(entity);
                context.SaveChanges();
                return entity;
            }

    Hope this will help you.

    Thanks,

    Wenushka

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 18, 2015 10:59 AM