entity-framework - 针对复杂类型属性的 Entity Framework 查询

标签 entity-framework linq-to-entities

我遇到了一个问题,即 Entity Framework 在尝试对复杂类型执行 OrderByDescending 或 Where 表达式时抛出 NotSupportedException。我不确定我是否做错了什么,但这个功能不存在似乎很令人惊讶。

例子:

假设我有一个名为 Person 的实体,它在数据库中有一组字段构成一个人的地址。在我的实体模型中,我会将这些字段建模为复杂类型,这样我就可以做

var city = person.Address.City;

映射这看起来很好,当我对复杂类型之外的任何属性执行 Linq 查询时,我得到了正确的结果

很好的例子:

var people = (from person in Context.People
              where person.LastName == "Smith"
              select person).ToList();

问题示例:

var people = (from person in Context.People
              where person.Address.City == "Cleveland"
              select person).ToList();

这将引发一个 NotSupportedException 并出现以下错误:

ComplexTypes The specified type member 'Address' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

同样,消息很明确,但令人惊讶的是,此功能并不存在,因为它似乎限制了使用复杂类型的能力。有什么想法或解决方法吗?

最佳答案

我曾经遇到过这个问题。

确保 Person.Address 是可设置的。这将导致问题。好玩吧?

public Address Address { get; } = new Address();

这将解决它。

public Address Address { get; set; } = new Address();

关于entity-framework - 针对复杂类型属性的 Entity Framework 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46122835/

相关文章:

c# - 使用 LINQ to SQL 左连接

c# - 尝试删除"Adding a relationship with an entity which is in the Deleted state is not allowed"set in optional relationship时出现"many"

javascript - 是否有类似于 JavaScript 中的 .Map() 的 C# 函数?

LINQ - 如何保持(复杂)结果有序?

linq - Linq to实体的OR条件的lambda表达式

c# - 'Project1.ID' 中的未知列 'where clause'

c# - 预加载和显式加载之间的区别

c# - 按 Entity Framework 中子列表的第一项对集合进行排序

c# - IEnumerable 与 IQueryable

.net - 如何在LINQ中向实体进行LEFT JOIN?