【问题标题】:Bitwise operations on enums based on attributes基于属性的枚举按位运算
【发布时间】:2020-03-13 06:27:01
【问题描述】:

我有相当大的枚举,其中包含自定义数字,例如

 public enum DataSources
    {
        Undefined = 0,
        [Description(nameof(Resources.Web))]
        Web = 1,
        [Description(nameof(Resources.Mail))]
        Email = 2, 
        [Parent(Value = (int)Other)]
        [Description(nameof(Resources.VoIP))]
        Voip = 5,
        [Parent(Value = (int)Other)]
        [Description(nameof(Resources.ProcessAndApplications))]
        Processes = 257,
        ...

现在我正在寻找一种将多个 DataSources(上面的枚举)值存储在另一个类中的方法,我们称之为 Role(它的 db 实体表示数据库中的行)。

class Role : DbEntity
{
        [PrimaryKey, Identity]
        public override long Id { get; set; }
        [Column(Name = "name"), NotNull]
        public string Name { get; set; }
        public DataSources dataSources {get;set;}
} 

通常我可以使用 [Flags],但我不能更改 DataSources 枚举的已分配值。 在这种情况下有什么解决办法吗?可能我可以为位值使用其他属性吗?

【问题讨论】:

  • 我已经添加了一些细节希望现在清楚了
  • Hrm hack... 存储逗号分隔值列表,创建非映射属性以提取和构建列表。或者只是创建另一个表
  • 在这里找到了可能有帮助的东西(如果您在 .net 核心上使用 EF)。尽管docs.microsoft.com/en-us/ef/core/modeling/value-conversions 我在.net 框架上找不到相同的EF 功能
  • @MichaelRandall 我希望你不建议存储comma-separated values in a database....
  • @ZoharPeled,哈哈,我的选择是位标志或其他表格,但我该判断谁:)

标签: c# enums


【解决方案1】:

您可以使用按位或将多个值存储在单个列中。但这要求所有枚举值都占用唯一的位。我已经看到这在你的情况下是不可能的,因为你有不止一个奇数。

下一个选项是将 DataSources 列提取到它自己的表中,并从 Role 中添加一个 FK。您的角色类更改如下所示。

class Role : DbEntity
{
    [PrimaryKey, Identity]
    public override long Id { get; set; }
    [Column(Name = "name"), NotNull]
    public string Name { get; set; }
    public IList<RoleDataSources> DataSources {get;set;}
}

class RoleDataSources : DbEntity
{
    [PrimaryKey, Identity]
    public override long Id { get; set; }
    [ForeignKey("Role"), Identity]
    public long RoleId { get; set; }
    public Role Role { get; set; }
    public DataSources Value { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-03-30
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 2018-04-20
    • 2020-10-07
    相关资源
    最近更新 更多