加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

如何将枚举映射为数据库中的字符串

发布时间:2020-12-12 16:25:00 所属栏目:MsSql教程 来源:网络整理
导读:我的桌子: create table MyTable ( Id int identity(1,1) not null,MyStatus char(2) not null)insert into MyTable(MyStatus) select 'A' 类和枚举: public class MyTable{ public virtual int Id { get; set; } public virtual MyTableStatus MyStatus {
我的桌子:
create table MyTable (
    Id int identity(1,1) not null,MyStatus char(2) not null
)
insert into MyTable(MyStatus) select 'A'

类和枚举:

public class MyTable
{
    public virtual int Id { get; set; }
    public virtual MyTableStatus MyStatus { get; set; }
}

public enum MyTableStatus
{
    A,B
}

制图:

public MyTableMap()
{
    Id(x => x.Id);
    Map(x => x.MyStatus);
}

当我执行以下测试时,我得到System.FormatException:输入字符串格式不正确…

[Test]
public void Blah()
{
    MyTable myTable = Session.Get<MyTable>(1);
    Assert.That(myTable.MyStatus,Is.EqualTo(MyTableStatus.A));
}

将枚举映射到数据库中的字符串表示形式的正确方法是什么?

编辑 – 我在现有数据库上编写应用程序,我无法轻易修改,因为它也被其他应用程序使用.所以数据库中的一些字段(我想在我的应用程序中表示为枚举)是int类型和一些char(2)类型.

解决方法

您需要创建自定义IUserType以将枚举转换为其字符串表示形式并返回.有一个 good example in C# here和一个 example in VB.NET for working with enums here(向下滚动到实现IUserType).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读