如何将枚举映射为数据库中的字符串 [英] How to map enum as string in database
问题描述
我的表:
创建表MyTable(
Id int identity(1,1)not null,
MyStatus char(2)not null
)
insert into MyTable(MyStatus)select'A'
类和枚举:
public class MyTable
/ pre>
{
public virtual int Id {get;组; }
public virtual MyTableStatus MyStatus {get;组; }
}
public enum MyTableStatus
{
A,
B
}
映射:
public MyTableMap()
{
Id(x => x.Id);
Map(x => x.MyStatus);
}
当我执行以下测试,我得到System.FormatException:输入字符串是不正确的格式...
[测试]
public void Blah()
{
MyTable myTable = Session.Get&MyTable>(1);
Assert.That(myTable.MyStatus,Is.EqualTo(MyTableStatus.A));
}
将枚举映射到数据库中的字符串表示形式的正确方法是什么? ?
编辑 - 我在现有的数据库上编写我的应用程序,我不能轻易修改,因为它也被其他应用程序使用。因此,数据库中的一些字段(我想在我的应用程序中以枚举形式表示)是int类型,一些类型为char(2)。
解决方案您需要创建一个自定义IUserType来将枚举转换为其字符串表示形式并返回。有一个 C#这里的好例子和一个在VB.NET中使用枚举的示例(向下滚动到实现IUserType)。
My table:
create table MyTable ( Id int identity(1,1) not null, MyStatus char(2) not null ) insert into MyTable(MyStatus) select 'A'
Class and enum:
public class MyTable { public virtual int Id { get; set; } public virtual MyTableStatus MyStatus { get; set; } } public enum MyTableStatus { A, B }
Mapping:
public MyTableMap() { Id(x => x.Id); Map(x => x.MyStatus); }
When I execute the following test, I get System.FormatException : Input string was not in a correct format...
[Test] public void Blah() { MyTable myTable = Session.Get<MyTable>(1); Assert.That(myTable.MyStatus, Is.EqualTo(MyTableStatus.A)); }
What is the right way to map an enum to it's string representation in the database?
Edit - I am writing my application on an existing database, which I cannot modify easily because it is used by other applications also. So some fields in the database (which I would like to represent as enums in my application) are of type int and some of type char(2).
解决方案You need to create a custom IUserType to convert an enum to its string representation and back. There's a good example in C# here and an example in VB.NET for working with enums here (scroll down to implementing IUserType).
这篇关于如何将枚举映射为数据库中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!