Enum datatype conversion to string












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










share|improve this question

























  • Could you please explain why must be a string?

    – Foo
    Nov 18 '18 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

    – None of the Above
    Nov 18 '18 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

    – Ehi
    Nov 18 '18 at 20:35
















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










share|improve this question

























  • Could you please explain why must be a string?

    – Foo
    Nov 18 '18 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

    – None of the Above
    Nov 18 '18 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

    – Ehi
    Nov 18 '18 at 20:35














0












0








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










share|improve this question
















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







c# asp.net-mvc class






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 18 '18 at 17:12









marc_s

576k12911111258




576k12911111258










asked Nov 18 '18 at 16:55









EhiEhi

145




145













  • Could you please explain why must be a string?

    – Foo
    Nov 18 '18 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

    – None of the Above
    Nov 18 '18 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

    – Ehi
    Nov 18 '18 at 20:35



















  • Could you please explain why must be a string?

    – Foo
    Nov 18 '18 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

    – None of the Above
    Nov 18 '18 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

    – Ehi
    Nov 18 '18 at 20:35

















Could you please explain why must be a string?

– Foo
Nov 18 '18 at 17:11





Could you please explain why must be a string?

– Foo
Nov 18 '18 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

– None of the Above
Nov 18 '18 at 17:26





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

– None of the Above
Nov 18 '18 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

– Ehi
Nov 18 '18 at 20:35





@TânNguyễn because the values in the database are of string. By the way, i watched your videos on youtube ? Great vids

– Ehi
Nov 18 '18 at 20:35












2 Answers
2






active

oldest

votes


















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.






share|improve this answer


























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

    – Ehi
    Nov 20 '18 at 11:59



















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/






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53363308%2fenum-datatype-conversion-to-string%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    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.






    share|improve this answer


























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

      – Ehi
      Nov 20 '18 at 11:59
















    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.






    share|improve this answer


























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

      – Ehi
      Nov 20 '18 at 11:59














    1












    1








    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.






    share|improve this answer















    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.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 19 '18 at 5:28

























    answered Nov 19 '18 at 5:23









    FooFoo

    1




    1













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

      – Ehi
      Nov 20 '18 at 11:59



















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

      – Ehi
      Nov 20 '18 at 11:59

















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

    – Ehi
    Nov 20 '18 at 11:59





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

    – Ehi
    Nov 20 '18 at 11:59













    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/






    share|improve this answer




























      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/






      share|improve this answer


























        0












        0








        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/






        share|improve this answer













        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/







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 30 '18 at 15:07









        EhiEhi

        145




        145






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53363308%2fenum-datatype-conversion-to-string%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to change which sound is reproduced for terminal bell?

            Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

            Can I use Tabulator js library in my java Spring + Thymeleaf project?