存储库模式 c# 中的枚举
Enumeration in Repository Pattern c#
如何从我的数据库中读取一个 int 属性,该属性在我的系统中是 C# 存储库模式中的枚举类型属性。
我做了一个class:
public class Status : Enumeration
{
public static readonly Status Active = new Status(0, "Active");
public static readonly Status Inactive = new Status(1, "Inactive");
public static readonly Status Removed = new Status(2, "Removed");
public Status()
{
}
private Status(int value, string displayName)
: base(value, displayName)
{
}
}
所以在 Bank class 我放了一个 Status 属性;
在从我的银行 class 所在的银行读取时,table 的属性 Status 类型为 int,加上属性为 null。
我会在你的 class 中引入一个将整数转换为 "enum" 的静态方法,例如
public class Status : Enumeration
{
//YOUR CODE
public static Status FromInteger(int value){
switch(value){
case 0:
return Active;
case 1:
return Inactive;
case 2:
return Removed;
default:
throw new ArgumentException();
}
}
}
我没有处理过DapperRepository。但快速查看 ClassMapper<T>
表明您可以使用 AutoMap 方法利用自定义转换。但是,我既没有找到文档也没有找到示例。
因此,我只能提出一个通用的解决方案。
public class Bank {
//Standard fields that are mapped to a table in database
public Status StatusEnum {
get {
Status.FromInteger(StatusId); //StatusId is a property mapped to table's field
}
set {
//TODO Handle null value
StatusId = value.Value;
}
}
}
注意:
- 我假设 属性
StatusId
是映射到 table 包含状态值的字段的字段。
- 这段代码有明显的问题 - StatusId 允许超出枚举范围的值。您将必须进行一些额外的验证以保持数据的一致性。
如何从我的数据库中读取一个 int 属性,该属性在我的系统中是 C# 存储库模式中的枚举类型属性。
我做了一个class:
public class Status : Enumeration
{
public static readonly Status Active = new Status(0, "Active");
public static readonly Status Inactive = new Status(1, "Inactive");
public static readonly Status Removed = new Status(2, "Removed");
public Status()
{
}
private Status(int value, string displayName)
: base(value, displayName)
{
}
}
所以在 Bank class 我放了一个 Status 属性;
在从我的银行 class 所在的银行读取时,table 的属性 Status 类型为 int,加上属性为 null。
我会在你的 class 中引入一个将整数转换为 "enum" 的静态方法,例如
public class Status : Enumeration
{
//YOUR CODE
public static Status FromInteger(int value){
switch(value){
case 0:
return Active;
case 1:
return Inactive;
case 2:
return Removed;
default:
throw new ArgumentException();
}
}
}
我没有处理过DapperRepository。但快速查看 ClassMapper<T>
表明您可以使用 AutoMap 方法利用自定义转换。但是,我既没有找到文档也没有找到示例。
因此,我只能提出一个通用的解决方案。
public class Bank {
//Standard fields that are mapped to a table in database
public Status StatusEnum {
get {
Status.FromInteger(StatusId); //StatusId is a property mapped to table's field
}
set {
//TODO Handle null value
StatusId = value.Value;
}
}
}
注意:
- 我假设 属性
StatusId
是映射到 table 包含状态值的字段的字段。 - 这段代码有明显的问题 - StatusId 允许超出枚举范围的值。您将必须进行一些额外的验证以保持数据的一致性。