Question :
How can I read from my database a int
attribute that in my system is an attribute of type Enumeration
in Repository Pattern
?
I made a 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)
{
}
}
Then in class Bank
I put an attribute of type Status
;
At the time of reading from the database where my class Bank
is a table with an attribute Status
type int
, but the attribute is null
.
How can I resolve this?
Answer :
Thanks for the messages, I have solved the problem.
Create the class that inherits from Enumeration the following:
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();
}
}**
}
Then in Bank class I did the following:
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;
}
}
}
Adding in addition a StatusId attribute that is the type attribute of the database and I’m stuck.
If you are using the Entity Framework it automatically identifies, ie saves as int in the database and creates the object with the enumeration. What I tell you to do is to change this enumeration to something like this:
public enum Status
{
Active,
Inactive,
Removed
}
Find out that enums are not saved in the database, it will be an int column of the table that has the enum as property.