How do I map a char property using the Entity Framework 4.1 “code only” fluent API?

前端 未结 5 1249
臣服心动
臣服心动 2020-12-01 15:27

I have an object that has a char property:

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

Entity Frame

5条回答
  •  醉梦人生
    2020-12-01 16:07

    I have tried all the ways I have imagined and I must say the the accepted answer is the unique way to solve the problem of the char type as far as I know.

    The char type isn't available for its use in EntityFramework.

    Fluent API is included in this restriction.

    If you try to put a char on the Property(p => p.MyCharProperty) will give you an Exception.

    That means that char properties aren't available for Fluent API nor Attributes.

    The easiest solution is this (as proposed by Ladislav Mrnka).

    public class Product
    {
        public char Code { get; set; }
    
        [Column("Code", TypeName="char")]
        [MaxLength(1)]
        public string CodeString
        {
             get { return Code.ToString(); }
             set { Code = value[0]; }
        }
    }
    

    One note: you can't put the property private, protected or internal. Must be public.

    Fluent API version would be like this.

    public class Product
    {
        public char Code { get; set; }
    
        //We need the property but we will use the Fluent API to replace the attributes
        public string CodeString
        {
             get { return Code.ToString(); }
             set { Code = value[0]; }
        }
    }
    

    modelBuilder.Entity().Property(p => p.Code)
        .HasTypeName("char")
        .HasMaxLength(1)
    

提交回复
热议问题