以下是我的课程
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;
由于
答案 0 :(得分:0)
int
不能为null,因为它是一种有价值的类型,因此无需将Required
属性添加到Uom1Id
和Uom2Id
。对于UI,您可以创建一个视图模型,其中Uom1Id
和Uom2Id
将为int?
(可为空)。