简体   繁体   English

如何使用EntityFramework代码先将tinyint映射到C#字节

[英]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. 我正在尝试将tinyint列映射到c#中的byte属性,如何有效地实现这一点。 I want to store the values null, 0 and 1 to the database column. 我想将值null,0和1存储到数据库列中。 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.) (我假设column属性是正确的-我对此一无所知。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用实体框架代码优先将 C# int 映射到 SqlServer tinyint? - How do I map a C# int to a SqlServer tinyint using Entity Framework Code First? 从数据库使用EntityFramework C#代码优先-如何在没有主键的情况下映射表 - Using EntityFramework C# code-first from database - how to map table with no primary key SQL Server中的tinyint到C#中的byte - tinyint in SQL Server to byte in C# MVC C#代码首次迁移 - MVC C# code first migration 如何首先使用mvc 5和EntityFramework代码将两个属性映射到同一张表? - How map two properties to the same table using mvc 5 and EntityFramework code first? 如何在EntityFramework Code First中参考另一个模型的列表来映射模型 - How to map a model with reference to a list of another model in EntityFramework Code First 如何使用EntityFramework将字节字符串存储在byte []中 - how to store byte string in byte[] using EntityFramework 如何映射元组 <something, something> 首先使用c#EF代码访问数据库? - How to map Tuple<something, something> to database using c# EF code first? 如何将tinyint映射到int? - How to map tinyint to int? EntityFramework 代码优先迁移忽略 [Key] 并强制使用复合键 - EntityFramework Code-first migration ignoring [Key] and forcing composite key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM