简体   繁体   English

在实体框架中基于数据库列值显示枚举文本

[英]Show enum text based on database column value in Entity Framework

I have a model that maps to database table, I have an enum property in that model. 我有一个映射到数据库表的模型,在该模型中有一个枚举属性。 I'm storing an int value in the table column and for managing things using enum for that (as I have small fix list). 我在表列中存储一个int值,并为此使用枚举来管理事物(因为我的修复列表很小)。

My question is I want the text of enum for particular db column value. 我的问题是我想要特定数据库列值的枚举文本。

public class Item
{
    public int ItemId { get; set; } // ItemId (Primary key)

    [Required]
    [DisplayName("Category")]
    public int? CategoryId { get; set; } // CategoryId

    [Required]
    public string Name { get; set; } // Name (length: 100)

    [DisplayName("Item Code")]
    public string ItemCode { get; set; } // ItemCode (length: 15)

    [DisplayName("Unit Type")]
    public int? UnitId { get; set; } // UnitId
    public DateTime? UpdatedOnUtc { get; set; } // UpdatedOnUtc
    public DateTime? CreatedOnUtc { get; set; } // CreatedOnUtc

    [DisplayName("Is Active")]
    public bool IsActive { get; set; } // IsActive

    // Reverse navigation
    public virtual ICollection<GatePass> GatePasses { get; set; }
    public virtual ICollection<MoveOrderItem> MoveOrderItems { get; set; }
    public virtual ICollection<ProjectItemPrice> ProjectItemPrices { get; set; }

    // Foreign keys
    public virtual Category Category { get; set; }

    [NotMapped]
    public Enums.UnitType UnitType { get; set; }
}

I'm storing enum value in UnitId column and for display it value I want to show text of that enum/enum display attribute. 我将枚举值存储在UnitId列中,为了显示该值,我想显示该枚举/枚举显示属性的文本。

My enum is UnitType : 我的枚举是UnitType

public enum UnitType
{
    Set = 1,
    Km = 2,
    No = 3,
    Kg = 4,
    Mtr = 5
}

My main purpose is to manage display in EF query because In EF list I will have UnitId but I want to display UnitType's unit text like kg,set,no,mtr etc.. 我的主要目的是管理EF查询中的显示,因为在EF列表中,我将具有UnitId但我想显示UnitType的单位文本,例如kg,set,no,mtr等。

I did this stuff often time in SQL using case when as but I don't know how to manage in EF. 我经常在用case when as使用SQL case when as但是我不知道如何在EF中进行管理。

You can change a UnitType property type to string and then read enum constant as below: 您可以将UnitType属性类型更改为string ,然后读取enum常量,如下所示:

public string UnitType 
{ 
   get
   { 
     return Enum.GetName(typeof(UnitType), UnitId); 
   } 
}

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

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