【发布时间】:2013-12-27 06:33:50
【问题描述】:
我有两个实体:
public class ParentThing
{
[Key]
public int Id { get; set; }
[Required]
public ChildThing TheFirstThing { get; set; }
public ChildThing TheSecondThing { get; set; }
}
public class ChildThing
{
[Key]
public int Id { get; set; }
[Required]
public string Code { get; set; }
public string Name { get; set; }
}
还有一个视图模型:
public class ParentViewModel
{
public string Message { get; set; }
public ParentThing ParentThing { get; set; }
}
还有一个观点:
@using (@Html.BeginForm())
{
<label>Code 1</label>
@Html.EditorFor(model => model.ParentThing.TheFirstThing.Code)
<label>Name 1</label>
@Html.EditorFor(model => model.ParentThing.TheFirstThing.Name)
<label>Code 2</label>
@Html.EditorFor(model => model.ParentThing.TheSecondThing.Code)
<label>Name 2</label>
@Html.EditorFor(model => model.ParentThing.TheSecondThing.Name)
<input type="submit" value="Save" />
}
在我的回帖中,我将 ParentThing 添加到上下文中并尝试保存更改。我收到有关 ParentThing 的 TheSecondThing 属性的 Code 属性的验证错误,因为它是必需的。
保存包含必需属性的可选属性有哪些替代方法?
【问题讨论】:
-
另一种方法是删除视图模型中对实体类的依赖。您想使用数据传输对象 (DTO)。这个stackoverflow.com/questions/5995140/… 将帮助您入门。
标签: c# asp.net-mvc entity-framework validation required