Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map a field to an enum in EntityFramework 5 Code First

So, I have a class as follows:

public class Message {

        public enum MessageType {
            Text = 0,
            Audio = 1,
            Image = 2
        }

        public int Uid { get; set; }
        public MessageType Type { get; set; }
        public String Text { get; set; }

}

As you can see, the Type field is an enum. My mapping to match up the data to this class is defined like this:

public class MessagesMap : EntityTypeConfiguration<Message> {

    public MessagesMap() {

        // Primary Key
        this.HasKey(t => t.Uid);

        // Properties
        this.Property(t => t.Text)
            .HasMaxLength(1000);

        // Table & Column Mappings
        this.ToTable("wc_messages");
        this.Property(t => t.Uid).HasColumnName("UID");
        this.Property(t => t.Type).HasColumnName("Type");
        this.Property(t => t.Text).HasColumnName("Text");

    }
}

But when I run the code, I get the following error:

The property 'Type' is not a declared property on type 'Message'. Verify that the property has not been explicitly excluded from the model by using the Ignore method or NotMappedAttribute data annotation. Make sure that it is a valid primitive property.

I understand I'm getting the error as the Type property is not a primitive, but an enum. If I understand correctly, though, EF5 supports enums (and I'm targeting the .NET 4.5 framework) so I assume I'm missing something in my mapping that's not explaining how to convert to the enum, but I'm at a loss as to what that is. If I change the field back to an int it all works fine, it's only when the field type is the enum that I get the error.

What am I missing? Thanks in advance.

like image 826
BinarySolo Avatar asked Mar 21 '13 13:03

BinarySolo


1 Answers

So it turns out I'm just stupid and had my enum block declared inside the POCO class and completely failed to notice it. I realised it thanks to a ninja comment from @overmachine (that subsequently disappeared) and moving the declaration out of my class caused everything to work fine again. Thanks go to him, wherever he went, and lesson learnt to be more attentive sigh

like image 77
BinarySolo Avatar answered Nov 12 '22 05:11

BinarySolo