Map string column in Entity Framework to Enum

前端 未结 8 1308
被撕碎了的回忆
被撕碎了的回忆 2021-02-18 13:46

Is there a way to map a string column to an enum in an Entity Model?

I have done this in Hibernate, but can\'t figure it out in EMF.

8条回答
  •  耶瑟儿~
    2021-02-18 14:30

    An alternative is to use a static class with string const fields instead of enums.

    For example:

    public class PocoEntity
    {
        public string Status { get; set; }
    }
    
    public static class PocoEntityStatus
    {
        public const string Ok = "ok";
        public const string Failed = "failed";
    }
    

    For added validation on the database side you can add a check constraint to verify that the column is the expected value (you can do this when mapping to an enum as well, but since the property is just a string this helps ensure the consumer of your api set the value properly).

    ALTER TABLE [PocoEntity]
        ADD CONSTRAINT [CHK_PocoEntity_Status]
        CHECK ([Status] in ('ok', 'failed'));
    

提交回复
热议问题