Skip to content

Get By Id Operations

Furkan Güngör edited this page Jun 20, 2022 · 2 revisions

Summary

With EasyRepository, your GetById queries can be run. However, the id value must be the primary key.

Get-By-Id

public class MyClass
{
    private readonly IUnitOfWork _unitOfWork;
    public MyClass(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    public async Task<Author> GetByIdAsync(Guid id)
    {
         var entity = await _unitOfWork.Repository.GetByIdAsync<Author>(asNoTracking:true, id);
         return entity;
    }
}

Get-By-Id With Select

public class MyClass
{
    private readonly IUnitOfWork _unitOfWork;
    public MyClass(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    public async Task<object> GetByIdWithSelectAsync(Guid id)
    {
        return await _unitOfWork.Repository.GetByIdAsync<Author,object>(true, id, projectExpression: select => new
            {
                SelectName = select.Name,
                SelectDate = select.CreationDate
            });
    }
}

Get-By-Id With Include

public class MyClass
{
    private readonly IUnitOfWork _unitOfWork;
    public MyClass(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    public async Task<object> GetByIdWithIncludeAsync(Guid id)
    {
        Func<IQueryable<Author>, IIncludableQueryable<Author, object>> include = a => a.Include(i => i.Books);
        return await _unitOfWork.Repository.GetByIdAsync<Author>(asNoTracking: true, id, includeExpression: include);
    }
}

Get-By-Id With Include And Select

public class MyClass
{
    private readonly IUnitOfWork _unitOfWork;
    public MyClass(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    public async Task<object> GetByIdWithIncludeAndSelectAsync(Guid id)
    {
        Func<IQueryable<Author>, IIncludableQueryable<Author, object>> include = a => a.Include(i => i.Books);
        return await _unitOfWork.Repository.GetByIdAsync<Author, object>(asNoTracking: true, id, projectExpression: select => new
            {
                SelectName = select.Name,
                SelectDate = select.CreationDate
            },includeExpression: include);
    }
}