C# – Entity Framework 5 complex type and unknown column in field list error

centity-framework

Bear with me as I'm new to C# and programming in general.

I'm trying to define a complex type that is in the same table as the principle class. Basically, it's the good old User and Address example.

public class Customer
{
    [Key]
    public int customerId { get; set; }

    //some attributes

    public string street { get; set; }
    public string city { get; set; }
    public string province { get; set; }
    public string country { get; set; }
    public string postal { get; set; }
}

So I try to slice off the address information into its own class:

public class Customer
{
    [Key]
    public int customerId { get; set; }

    //some attributes
    public Address address { get; set; }
}

[ComplexType]
public class Address
{
    public string street { get; set; }
    public string city { get; set; }
    public string province { get; set; }
    public string country { get; set; }
    public string postal { get; set; }
}

I get no compile error and when I load a view that access the Customer model, I get an unknown column in field set error.

Unknown column 'Extent1.address_street' in 'field list'

I basically followed this example: http://weblogs.asp.net/manavi/archive/2010/12/11/entity-association-mapping-with-code-first-part-1-one-to-one-associations.aspx

Is there something I"m missing or something different with EF5?

Best Answer

By default EF expects columns for properties of complex types in form {complextypename_propertyname}. If you created your tables manually and named columns differently there will be a mismatch. Can you try renaming the columns accordingly (i.e. street to address_street) and try if it works. Alternatively you should be able to add an attribute to the properties on the complex type to tell EF that is should not use the convention but the name you specified (e.g. [Column("street")] for the street property).

Related Topic