12

When I try to map a column to a char data type in my model class I get an error:

The property '[ColumnName]' is not a declared property on type '[ClassName]'. 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.

What are the valid primitive types for EF Code First?

Ryan
  • 4,602
  • 8
  • 37
  • 43

1 Answers1

19

This is interesting but you really cannot map char property. I just checked it and if you want to have char(1) in the database you must use string property with following mapping:

modelBuilder.Entity<MyEntity>()
            .Property(p => p.MyProperty)
            .HasMaxLength(1)
            .IsFixedLength()
            .IsUnicode(false);

It is not only problem of Code-first. It is whole EF limitation because EDMX designer also doesn't show char type. I think allowed types will be same as described in CSDL reference for EDMX because code first is just wrapper around the same mapping infrastructure.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Hehe "What are the valid primitive types for EF Code First?" – X181 Mar 30 '12 at 12:32
  • Hint: The error occures also if you have a property with a private setter. In my case the property was in a base class. – X181 Mar 31 '12 at 08:39
  • I had a Check Constraint on a char field to make it equal to one of 2 characters. If I didn't have `.HasMaxLength(1)`, it would allow the value to be saved without checking what it was, but if I had it, it would enforce the constraint. Just an odd bit of trivia I found out. – vapcguy Sep 19 '18 at 20:32
  • There is alternate ways to tackle this issue for TESTING purpose only. Make the field not null to null able for time being from design mode. Sometime it is restricted SQL Management Studio. (Change setting Tools -> Option ->Designer -> Table Database designer -> Uncheck "Prevent saving changes that required table creation" – Manoj Patil Dec 04 '18 at 12:18