ardalis / Specification

Base class with tests for adding specifications to a DDD model
MIT License
1.81k stars 238 forks source link

Search in result dto object instead of db class #394

Open ertugrulkaya opened 2 weeks ago

ertugrulkaya commented 2 weeks ago

Search option in result dto object instead of db class.

I have 3 classes; Material , Material Type and Material Group.

Material includes the material type and material group.

When I show list of materials including material type name to clients , client want search material type name ? But this filed is not in same db table.

How we can do it ? What is the best case ?

enrij commented 2 weeks ago

If I got it right, specification and EF Core should handle your request already:

// Assuming Material having a property Type of type MaterialType

internal sealed class MaterialByMaterialTypeNameSpecification : Specification<Material>
{
    internal MaterialByMaterialTypeNameSpecification(string name)
    {
        // Deal with an empty name
        ArgumentException.ThrowIfNullOrEmpty(name);

        Query.Where(material => material.Type.Name == name)
    }
}

// Somewhere in your code
{
    private readonly IRepositoryBase<Material> _repository;

    // ...

    public void Bar(CancellationToken cancellationToken = default)
    {
        var specification = new MaterialByMaterialTypeNameSpecification("Foo");
        List<Material> materials = await _repository.ListAsync(specification, cancellationToken);
        // Do something with the returned materials
    }
}