Reputation: 43
How do I convert an enum datatype from int to string?
Here is my code below
public class Users_Accounts
{
[Key]
public int AccountID { get; set; }
public Guid UniqueID { get; set; }
[EnumDataType(typeof(string), ErrorMessage = "{0} Opps")]
public Title Title { get; set; }
public string First_Name { get; set; }
public string Last_Name { get; set; }
}
and here is my Title
enum:
public enum Title
{
Mr, Mrs, Miss, Chief
}
I get the error
InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int32'.
I know enums are strongly type and have a value of int, and in my database its nvarchar(20)
How do I convert it?
Many thanks
Upvotes: 0
Views: 1169
Reputation: 43
I also found this online, and though its MVC 5 changing View.Bag to View["Data"] it works
Upvotes: 0
Reputation: 1
I will provide you an example that you can try but it's just a quick solution since you didn't design database structure.
Enum item:
public enum Title
{
Mr,
Mrs,
Miss,
Chief
}
By default, Title.Mr
should have the default value 0
, Mrs
has value 1
..., same to the orthers.
If you have 256 items or lower in the enum, you could try:
public enum Title : byte
{
Mr = 0,
Mrs = 1,
Miss = 2,
Chief = 3
}
Title.Mr
still has value 0
.
The entity:
public class Users_Accounts
{
[Key]
public int AccountID { get; set; }
public Guid UniqueID { get; set; }
//You can change the returned type of `Title` property from `Title` to `string` here
public string Title { get; set; }
public string First_Name { get; set; }
public string Last_Name { get; set; }
}
The model:
public class AddUserViewModel
{
public Title Title { get; set; }
public string First_Name { get; set; }
public string Last_Name { get; set; }
}
When updating to database, you need to convert enum to a string:
public IActionResult AddUser(AddUserViewModel model)
{
// title contains value like: 0, 1, 2... as string
string title = ((int)model.Title).ToString();
var user = new Users_Accounts
{
AccountID = ...
UniqueID = ...
Title = title,
First_Name = model.First_Name,
Last_Name = model.Last_Name
};
_dbContext.UserAccounts.Add(user);
_dbContext.SaveChanges();
}
When you get some user, you can convert the Title
as string to enum:
var user = _dbContext.UserAccounts.SingleOrDefault(x => x.AccountID == 1);
Title userTitle = (Title)Convert.ToInt32(user.Title);
userTitle
would return Title.Mr
or Title.Mrs
...
NOTE: If you decide to use
public enum Title : byte {}
You need to change Convert.ToInt32
to Convert.ToByte
instead.
Upvotes: 1