枚举数据类型转换为字符串


如何将枚举数据类型从int转换为string?

这是我在下面的代码

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; }
}

这是我的Title枚举:

public enum Title
{
Mr, Mrs, Miss, Chief 
}

我得到错误

InvalidCastException:无法将"System.String"类型的对象强制转换为"System.Int32"类型。

我知道枚举是强类型的,值为int,在我的数据库中它的nvarchar(20)

如何转换?

非常感谢

我将为您提供一个可以尝试的示例,但这只是一个快速解决方案,因为您没有设计数据库结构。

枚举项:

public enum Title
{
Mr, 
Mrs, 
Miss, 
Chief 
}

默认情况下,Title.Mr应具有默认值0Mrs具有值1。。。,其他人也一样。

如果你的枚举中有256个或更低的项目,你可以尝试:

public enum Title : byte
{
Mr = 0, 
Mrs = 1, 
Miss = 2, 
Chief = 3
}

CCD_ 7仍然具有值CCD_。

实体:

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; }
}

型号:

public class AddUserViewModel
{
public Title Title { get; set; }
public string First_Name { get; set; }
public string Last_Name { get; set; }
}

当更新到数据库时,您需要将enum转换为字符串:

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();
}

当你得到一些用户时,你可以将Title作为字符串转换为enum:

var user = _dbContext.UserAccounts.SingleOrDefault(x => x.AccountID == 1);
Title userTitle = (Title)Convert.ToInt32(user.Title);

userTitle将返回Title.MrTitle.Mrs。。。

注意:如果您决定使用

public enum Title : byte {}

您需要将Convert.ToInt32改为Convert.ToByte

我在网上也发现了这一点,尽管它的MVC 5将View.Bag更改为View["Data"],但它可以

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

最新更新