Skip to content

GetById Operations

Furkan Güngör edited this page Dec 3, 2021 · 1 revision

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 IRepository repository;
    public MyClass(IRepository repository)
    {
        this.repository = repository;
    }

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

Get-By-Id With Select

public class MyClass
{
    private readonly IRepository repository;
    public MyClass(IRepository repository)
    {
        this.repository = repository;
    }

    public async Task<object> GetByIdWithSelectAsync(Guid id)
    {
        return await 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 IRepository repository;
    public MyClass(IRepository repository)
    {
        this.repository = repository;
    }

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

Get-By-Id With Include And Select

public class MyClass
{
    private readonly IRepository repository;
    public MyClass(IRepository repository)
    {
        this.repository = repository;
    }

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