首页 > 解决方案 > 如何在 LINQ 中使用自有类型?

问题描述

在 Entity Framework Core 2.2.6 中使用拥有类型,我将如何编写一个作用于拥有类型相等性的 LINQ 查询?

我正在构建一个使用 DDD 概念(如实体和值对象)的应用程序。例如,一个Person有一个PersonNamePersonName是一个提供相等方法和运算符的值对象。

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
    }
}

例如,我需要在我的数据库中找到所有名字和姓氏相同的人。

我试过的:

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"));

这编译并运行,但它返回一个空集合。

标签: c#entity-framework-coreddd-repositories

解决方案


尝试按单独的字段过滤:

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;
}

推荐阅读