我的表:
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)。
关于string - 如何将枚举映射为数据库中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4637000/