可选属性中的MVC必需属性

Jam*_*mie 6 c# validation asp.net-mvc entity-framework required

我有两个实体:

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; }
}
Run Code Online (Sandbox Code Playgroud)

和视图模型:

public class ParentViewModel
{
    public string Message { get; set; }

    public ParentThing ParentThing { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

和一个观点:

@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" />
}
Run Code Online (Sandbox Code Playgroud)

在我的帖子中,我将ParentThing添加到上下文并尝试保存更改.我在ParentThing的TheSecondThing属性的Code属性上收到验证错误,因为它是必需的.

保存包含必需属性的可选属性有哪些替代方法?

Leo*_*Leo 0

正如杰米建议的那样,删除实体和模型之间的任何依赖关系......它们是两个独立的事物,不要在实体上使用数据注释,而在模型上使用数据注释。删除模型的 ParentThing 属性,并根据需要在模型中添加原始属性(即 Message、ParentThingId、TheFirstThingId、TheFirstThingCode、TheFirstThingName 等),并将所有数据注释属性添加到模型中。如果您需要验证您的实体(您可能会),请在您的业务逻辑上执行此操作。

我希望这是有道理的

利奥.