[英]Entity Framework enum attribute to table column (code-first approach)
In ASP.NET I'm using Entity Framework with a code-first approach and I want based on my model to generate the DB table. 在ASP.NET中,我正在以代码优先的方式使用Entity Framework,并且我希望基于我的模型来生成DB表。 One of the attributes is Enum value, and it is not showing as a column in the generated table. 属性之一是Enum值,并且在生成的表中未显示为列。
So this is my enum: 所以这是我的枚举:
public enum MyEnum
{
val_one = 1,
val_two = 2,
val_three = 3
}
And this is my model: 这是我的模型:
public class MyModel
{
public int Id { get; set; }
public string attrString { get; set; }
public double attrDouble { get; set; }
public MyEnum attrEnum { get; set; }
}
So with the code-first approach I'm having generated table with the following columns: 因此,使用代码优先方法,我已经生成了具有以下列的表:
CREATE TABLE [dbo].[MyModel]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[attrString] NVARCHAR (MAX) NOT NULL,
[attrDouble] FLOAT (53) NOT NULL,
[attrEnum] INT NOT NULL,
CONSTRAINT [PK_dbo.MyModel] PRIMARY KEY CLUSTERED ([Id] ASC)
);
And later when generating forms (controller and views) based on the model, I'm having a forms where attrEnum
param is missing. 之后,当基于模型生成表单(控制器和视图)时,我遇到了缺少attrEnum
参数的表单。
So how to proceed in order to have this enum attribute (in format of dropdown list) in the forms (still using code-first approach). 因此,如何继续以表格的形式拥有此枚举属性(以下拉列表的格式)(仍然使用代码优先方法)。 I guess there may be needed generation of another DB table that will contains enums, but I'm really not sure how to do that in Entity Framework since I'm beginner in it. 我猜可能需要生成另一个包含枚举的数据库表,但是我真的不确定如何在Entity Framework中做到这一点,因为我是初学者。
You could take an easier approach... 您可以采取更简单的方法...
In the controller, for example: 在控制器中,例如:
public ActionResult Edit(int? id)
{
List<SelectListItem> myOptions = new List<SelectListItem>();
myOptions.Add(new SelectListItem() { Text="1", Value = "1" });
myOptions.Add(new SelectListItem() { Text = "2", Value = "2" });
myOptions.Add(new SelectListItem() { Text = "3", Value = "3" });
ViewData["OptionList"] = new SelectList(myOptions, "Value", "Text");
Then in the Edit.cshtml: 然后在Edit.cshtml中:
@Html.DropDownListFor(model => model.Status, (SelectList)ViewData["OptionList"], new { @class = "form-control dropdown" })
You get a nice styled dropdown with options you're looking for. 您会得到一个不错的样式下拉列表,其中包含您要寻找的选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.