0

下面是我的课

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,但它适用于我其他类中的其他字段。

具有键“Uom1Id”的 ViewData 项属于“System.Int32”类型,但必须属于“IEnumerable”类型。

谢谢

4

1 回答 1

0

int不能为空,因为它是有价值的类型,所以不需要在and中添加Required属性。对于 UI,您可以创建一个视图模型,其中和将是(可为空的)。Uom1IdUom2IdUom1IdUom2Idint?

于 2012-03-28T11:28:50.980 回答