Search code examples
c#entity-framework-coreddd-repositories

How to use Owned Types in LINQ?


Using Owned Types in Entity Framework Core 2.2.6, how would I write a LINQ query that acts on the equality of an owned type?

I'm building an application that uses DDD concepts like Entities and Value Objects. E.g. a Person has a PersonName. The PersonName is a Value Object that provides equality methods and operators.

public sealed class PersonConfiguration : IEntityTypeConfiguration<Person>
{
    public void Configure(EntityTypeBuilder<Person> entity)
    {
        entity.HasKey(its => its.Id);
        entity.OwnsOne(its => its.Name);
    }
}

public class Person
{
    private Person() { }

    public Person(Guid id, PersonName name) => (Id, Name) = (id, name);

    public Guid Id { get; private set; }

    public PersonName Name { get; private set; }
}

public class PersonName
{
    private PersonName() { }

    public PersonName(string firstName, string lastName) => (FirstName, LastName) = (firstName, lastName);

    public string FirstName { get; private set; }

    public string LastName {get; private set; }

    protected static bool EqualOperator(PersonName left, PersonName right)
    {
        // Omitted: equality check
    }

    protected static bool NotEqualOperator(PersonName left, PersonName right)
    {
        // Omitted: inequality check
    }

    public override bool Equals(object? obj)
    {
        // Omitted: equality check
    }

    public override int GetHashCode()
    {
        // Omitted: hashcode algorithm
    }
}

As an example, I need to find all people in my database that have the same first and last name.

What I've tried:

private readonly PersonContext Db = new PersonContext();
public IEnumerable<Person> FindByName(PersonName name)
{
    return from person in Db.People
           where person.Name == name
           select person;
}
---
var johnDoes = FindByName(new PersonName("John", "Doe"));

This compiles and runs, but it returns an empty collection.


Solution

  • Try to filter by separate fields:

    public IEnumerable<Person> FindByName(PersonName name)
    {
    return from person in Db.People
           where person.Name.FirstName == name.FirstName && person.Name.LastName == name.LastName
           select person;
    }