c# – Requiring a unique entity name in domain logic

Question:

When you write applications, starting to think from the base, and not from the domain logic, many things seem simple and straightforward. Let's say some entity in the DataAccess project:

public class Brand
{
    public int ID { get; set; }

    [Required]
    [Index(IsUnique = true)]
    [MaxLength(50)]
    public string Name { get; set; }
}

And I understand everything: primary key ID, required field Name, maximum nvarchar (50), all records in the table are unique.

And when you start thinking the same thing in terms of "think the domain logic first," questions start.

For example, I started the same design from the domain and started a class in the Domain project:

public class Brand
{
    public Brand(string name)
    {
        this.Name = name;
    }

    public string Name { get; private set; }
}

And I immediately thought about two things:

  • How do I specify that objects should have unique names?
  • How can I verify that this condition is met in unit tests for a domain project?

Is this even possible in principle?

When we have a set / set of objects, then they cannot be in a void, but only in some kind of storage (I do not use this word in terms of a storage layer).

For example, you can store it in a List or Array – but it is best to store it in a Dictionary with the Name key (the uniqueness condition will be provided automatically).

(True, in this case there are also problems: it is not clear what to do if we should have two or more unique fields on one object.)

Nevertheless, here are some additional questions that arise:

  • Is it possible at all at the domain level to require the uniqueness of fields (and is it necessary)? Or are these requirements possible only when persistence / DB layer appears?
  • What if an entity has more than two unique fields? (example, perhaps not the best: entity "legal entity", fields "full name of legal entity", "abbreviated name of legal entity" and "TIN" must be unique)

Update After rereading the article Entity vs Value Object: a complete list of differences in the "types of equivalence" part, it probably makes sense to clarify that Brand is a full-fledged entity, not a Value Object:

public class Brand
{
    public Brand(string name)
    {
        this.Name = name;
    }

    public int ID { get; set; }

    public string Name { get; private set; }
}

Answer:

Revising one of my favorite repositories with an example of a project built on the basis of DDD approach , it seems that I figured out in which direction to look for the right answer.

Summary of issue Unique customer name validation

This kind of check cannot be done using a Validator in the domain layer.

When creating your entity, it is necessary to make a call to the repository on the subject "is there already such an instance".

Scroll to Top