Search code examples
entity-frameworklinq-to-entities

Entity Framework Query against complex type properties


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.

Example:

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;

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

Fine Example:

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

Problem Example:

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

This throws a NotSupportedException with the following error:

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?


Solution

  • I've had this problem once.

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

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

    This will fix it.

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