Home > Enterprise >  How do I return the Id of a newly created asyncronous record in entity framework using a generic rep
How do I return the Id of a newly created asyncronous record in entity framework using a generic rep

Time:09-23

In my web application a form is submitted by the user to a controller which posts the model data and creates a new record. I want to return the Id of that newly created record which I'm struggling to do. My code looks like this:

public IActionResult Create_Requirement(Requirement model) 
{
    try {
        _requirement.CreateAsync(model);
        //I tried using reflection and it didn't work
        var IdProperty = model.GetType().GetProperty("Id").GetValue(model, null);

        return Json(new { success = true, data = model });
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    return Json(new { success = false, data = model });
}

At first I tried reflection, then I tried to calling the id from the model which returned 0. For clarity the structure of my repository is as follows:

IRepository

 public interface IRepository<TEntity> where TEntity : class
{
    IQueryable<TEntity> GetAll();
    Task<TEntity> CreateAsync(TEntity entity);
    Task<TEntity> UpdateAsync(TEntity entity);
    Task<TEntity> DeleteAsync(TEntity entity);
}

Repository

public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
    #region Fields
    protected readonly MyContext _context;
    #endregion

    public Repository(MyContext context)
    {
        _context = context;
    }

    #region Public Methods
    public IQueryable<TEntity> GetAll()
    {
        try
        {
            return _context.Set<TEntity>();
        }
        catch (Exception ex)
        {
            throw new Exception($"Couldn't retrieve entities: {ex.Message}");
        }
    }        
    public async Task<TEntity> CreateAsync(TEntity entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException($"{nameof(CreateAsync)} entity must not be null");
        }

        try
        {
            await _context.AddAsync(entity);
            await _context.SaveChangesAsync();

            return entity;
        }
        catch (Exception ex)
        {
            throw new Exception($"{nameof(entity)} could not be saved: {ex.Message}");
        }
    }
    public async Task<TEntity> DeleteAsync(TEntity entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException($"{nameof(CreateAsync)} entity must not be null");
        }

        try
        {
            _context.Remove(entity);
            await _context.SaveChangesAsync();

            return entity;
        }
        catch (Exception ex)
        {
            throw new Exception($"{nameof(entity)} could not be saved: {ex.Message}");
        }
    }
    public async Task<TEntity> UpdateAsync(TEntity entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException($"{nameof(CreateAsync)} entity must not be null");
        }

        try
        {
            _context.Update(entity);
            await _context.SaveChangesAsync();

            return entity;
        }
        catch (Exception ex)
        {
            throw new Exception($"{nameof(entity)} could not be updated: {ex.Message}");
        }
    }
    #endregion
}

Is there anyway I can get the id of the new record easily for use on the client side?

CodePudding user response:

Unless there is something I am missing, you are obviously returning the entity in the CreateAsync. Simply assign a variable to the method call and retrieve the id.

var user = requirement.CreateAsync(model);
var id = user.Id;

If it still doesn't return the id, likely the entity state of the model is not getting modified when it is created. Then just add these lines to the CreateAsync to retrieve entity after creation.

...
await _context.AddAsync(entity);
await _context.SaveChangesAsync();

entity = await _context.Set<TEntity>().FirstOrDefaultAsync();
return entity;

CodePudding user response:

AddAsync returns the information on the newly created entity. Use that.

var entity = await _context.AddAsync(entity);

  • Related