0

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

3
  • Could you please explain why must be a string? Commented Nov 18, 2018 at 17:11
  • An enum for an honorific seems a bad idea since they are so often optional - some people do not like to say and if their title was Khaleesi of the Great Grass Sea, Breaker of Chains, Mother of Dragons well, you missed that one Commented Nov 18, 2018 at 17:26
  • @TânNguyễn because the values in the database are of string. By the way, i watched your videos on youtube ? Great vids Commented Nov 18, 2018 at 20:35

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Must say, this is quite intelligent coding and it works. Thank you
0

I also found this online, and though its MVC 5 changing View.Bag to View["Data"] it works

https://www.c-sharpcorner.com/article/different-ways-bind-the-value-to-razor-dropdownlist-in-aspnet-mvc5/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.