How can I use the Entity Framework 4.1 "code only" fluent API to map a char property?

char ef4-code-only entity-framework fluent-interface

Question

I have an object with the attribute "char":

public class Product
{
    public char Code
    {
        get;
        set;
    }
}

It seems that Entity Framework cannot map characters (this field is missing from the database when I create the database schema from my model objects). Can I use the fluent API to map the char (for instance, to a string)? Since the model objects are a part of an old common library, I don't want to modify them.

1
46
7/20/2011 10:55:09 AM

Accepted Answer

Char is not a legitimate primitive type for an entity framework, hence it cannot be mapped. Zzz-6-Zzz will display a list of valid kinds if you tick it.char not one of them).

Database char(1) is equivalent tostring (CSDL to SQL conversion). Char has the description 1 fixed-length non-unicode string.

Second mapped property utilizing string and your choice is the only unattractive alternative.char Property not mapped will only be usedstring[0] from their premises. That is simply one more illustration of how much needed simple type mapping or converters are in EF.

73
5/23/2017 12:17:55 PM

Popular Answer

Using the HasColumnType function in Fluent API, you may define the database column data type in the following way:

modelBuilder.Entity<Product>()   
.Property(p => p.Code)   
.HasColumnType("char");

According to Andre Artus' response here, EF4.1 supports HasColumnType.

The ColumnAttribute may achieve the same result when used with Data Annotations.

[Column(TypeName="char")]
public string Code { get; set; }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow