简体   繁体   中英

How to map tinyint to c# byte using entityframework code first migration

I am trying to map tinyint column to byte property in c#How to achieve this efficiently. I want to store the values null, 0 and 1 to the database column. Please find below my code. Can anyone help me whether the following is the right approach?

public enum TriState : byte
{
    Null = 0,
    True = 1,
    False =2
}

[NotMapped]
public TriState AuthorisationStatus { get; set; }

[Column("AuthorisationStatus")]
public byte AuthorisationStatusByte {
    get
    {
        return Convert.ToByte(AuthorisationStatus.ToString());
    }
    private set
    {
        AuthorisationStatus = EnumExtensions.ParseEnum<TriState>(value);
    }
}

public static T ParseEnum<T>(byte value)
{
    return (T)Enum.Parse(typeof(T), value.ToString(), true);
}

Thanks

There's no need to go via a string at all. Just use the explicit conversions:

[Column("AuthorisationStatus")]
public byte AuthorisationStatusByte
{
    get { return (byte) AuthorisationStatus; }
    set { AuthorisationStatus = (TriState) value; }
}

(I'm assuming the column attribute is correct - I don't know about that side of things.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM