针对复杂类型属性的实体框架查询 [英] Entity Framework Query against complex type properties

查看:68
本文介绍了针对复杂类型属性的实体框架查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been running into an issue where Entity Framework is throwing a NotSupportedException when trying to do an OrderByDescending or Where expression on a complex type. I'm not sure if I'm doing something wrong but this seems quite surprising that this capability wouldn't exist.

示例:

假设我有一个名为Person的实体,该实体在数据库中具有一组构成一个人的Address的字段.在我的实体模型中,我会将那些字段建模为复杂类型,以便能够做到

Let's say I have an Entity called Person which in the database has a set of fields that make up a person's Address. In my entity model, I would model those fields as a complex type so that I could do

var city = person.Address.City;

这似乎很好,并且当我对复杂类型之外的任何属性进行Linq查询时,我会得到正确的结果

Mapping this seems fine and, when I do a Linq query against any properties outside of the complex type, I get proper results

很好的例子:

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并显示以下错误:

This throws a NotSupportedException with the following error:

ComplexTypes在以下版本中不支持指定的类型成员地址" LINQ到实体.仅初始化器,实体成员和实体 导航属性受支持.

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

同样,该消息很清楚,但令人惊讶的是该功能不存在,因为它似乎限制了使用复杂类型的功能.有任何想法或解决方法吗?

Again, the message is clear but quite surprising that this capability doesn't exist as it seems like it limits the ability to use complex types. Any ideas or workarounds?

推荐答案

我曾经遇到过这个问题.

I've had this problem once.

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

Make sure that Person.Address is Settable. This will cause the problem. Fun right?

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

这将解决它.

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

这篇关于针对复杂类型属性的实体框架查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆