Search code examples
c#asp.net-corerepositoryaspnetboilerplateasp.net-boilerplate

How to get entity by specific field (not primary key)?


I have done get data by Id (primary key) with success. But if I call Get by another field, why is it always Id that is used?

search with id(primary key)

Search with id_kategori(not_primary_key

Here is my code:

ITempatAppService.cs

public interface ITempatAppService:IApplicationService
{
    GetTempatOutput GetTempatById(GetTempatInput input);

    GetTempatOutput GetTempatByIdKategori(GetTempatKategori input);
}

GetTempatInput.cs

public class GetTempatInput
{
    public int Id { get; set; }
}

GetTempatOutput.cs

public class GetTempatKategori
{
    public int IdKategori { get; set; }
}

TempatAppService.cs

public class TempatAppService:ApplicationService,ITempatAppService
{
    private readonly ITempatManager _tempatManager;
    public TempatAppService(ITempatManager tempatManager)
    {
        _tempatManager = tempatManager;
    }

    public GetTempatOutput GetTempatById(GetTempatInput input)
    {
        var getTempat = _tempatManager.GetTempatById(input.Id);
        GetTempatOutput output = Mapper.Map<MasterTempat, GetTempatOutput>(getTempat);
        return output;
    }

    public GetTempatOutput GetTempatByIdKategori(GetTempatKategori input)
    {
        var getTempat = _tempatManager.GetTempatByIdKategori(input.IdKategori);
        GetTempatOutput output = Mapper.Map<MasterTempat, GetTempatOutput>(getTempat);
        return output;
    }
}

Here is my TempatManager.cs:

public class TempatManager : DomainService, ITempatManager
{
    private readonly IRepository<MasterTempat> _repositoryTempat;
    public TempatManager(IRepository<MasterTempat> repositoryTempat)
    {
        _repositoryTempat = repositoryTempat;
    }

    public MasterTempat GetTempatById(int Id)
    {
        return _repositoryTempat.Get(Id);
    }

    public MasterTempat GetTempatByIdKategori(int IdKategori)
    {
        return _repositoryTempat.Get(IdKategori);
    }
}

Solution

  • Naming the parameter IdKategori doesn't make it search by that column. Do this:

    public MasterTempat GetTempatByIdKategori(int IdKategori)
    {
        return _repositoryTempat.GetAll().First(t => t.IdKategori == IdKategori);
    }