c# - 如何在 LINQ 中使用自有类型?
问题描述
在 Entity Framework Core 2.2.6 中使用拥有类型,我将如何编写一个作用于拥有类型相等性的 LINQ 查询?
我正在构建一个使用 DDD 概念(如实体和值对象)的应用程序。例如,一个Person有一个PersonName。PersonName是一个提供相等方法和运算符的值对象。
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"));
这编译并运行,但它返回一个空集合。
解决方案
尝试按单独的字段过滤:
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;
}
推荐阅读
- python - 如何通过 SSH 访问多台 PC,并在每台 PC 中独立运行一个代码库
- tensorflow - 预期 time_distributed_38_input 有 5 个维度,但得到了形状为 (13974, 100, 6, 5) 的数组
- domo - 如何在不全部删除的情况下连续省略某些数据?
- javascript - JS匹配来自不同数组的字符串
- javascript - 表 - 基于列内容长度的列数
- javascript - 如何验证促销输入字段?
- java - ForEach 循环中断和加入线程
- jquery - 追加 div,当特定文本出现在元素中时。当特定文本消失时将其返回到原始位置
- html - Next.js 从/到另一个页面重定向
- haskell - 如何使用具有 2 个值的显示功能