我遇到了一个问题,即 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/