asp.net mvc代码优先。需要下拉列表

时间:2012-03-28 11:24:05

标签: entity-framework attributes code-first required

以下是我的课程

public class Item
{
    public int ItemID { get; set; }

    [Required(ErrorMessage = "Unit of measure1 is required.")]
    public int Uom1Id { get; set; }
    public UnitOfMeasure Uom1 { get; set; }

    [Required(ErrorMessage = "Unit of measure2 is required.")]
    public int Uom2Id { get; set; }
    public UnitOfMeasure Uom2{ get; set; }
}

public class UnitOfMeasure
{
    public int UnitOfMeasureID { get; set; }
    public string MeasureName { get; set; }
}

我的初始化程序如下:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Entity<Item>().HasRequired(x => x.StockUnitOfMeasure)
       .WithMany()
       .HasForeignKey(x => x.StockUnitOfMeasureId).WillCascadeOnDelete(false);

        modelBuilder.Entity<Item>().HasRequired(x => x.PurchaseUnitOfMeasure)
           .WithMany()
           .HasForeignKey(x => x.PurchaseUnitOfMeasureId).WillCascadeOnDelete(false);

    }

创建代码:

<div class="editor-label">
        @Html.LabelFor(model => model.Uom1Id, "Stock Unit Of Measure")
    </div>
    <div class="editor-field">
        @Html.DropDownList("Uom1Id", String.Empty)
        @Html.ValidationMessageFor(model => model.Uom1Id )
    </div>

我是EF的新手,我不知道为什么属性[Required]对字段Uom1Id和Uom2Id不起作用,但它适用于我其他类中的其他字段。

  

具有键&#39; Uom1Id&#39;的ViewData项。是的   输入&#39; System.Int32&#39;但必须是类型   &#39; IEnumerable的&#39;

由于

1 个答案:

答案 0 :(得分:0)

int不能为null,因为它是一种有价值的类型,因此无需将Required属性添加到Uom1IdUom2Id。对于UI,您可以创建一个视图模型,其中Uom1IdUom2Id将为int?(可为空)。