如何在LINQ中使用拥有的类型?

问题描述 投票:0回答:1

在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-core ddd-repositories
1个回答
0
投票

尝试按单独的字段进行过滤:

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.