假设我有一个示例实体:
public class City
{
public int CityId { get; set; }
public string Name { get; set; }
public int StateId { get; set; }
public virtual State State{ get; set; }
}
有几种情况会创建新城市。1)由用户在视图中,从现有状态中选择:
@Html.DropDownListFor(it => it.StateId, ViewBag.States)
2)在状态可能是新的情况下的后端:
State newState = context.States.Create();
newState.Name = "North Takoma";
City newCity = context.Cities.Create();
newCity.Name = "Springfield";
newCity.State = newState;
context.States.Attach(newState);
context.Cities.Attach(newCity);
context.SaveChanges();
状态关系是必需的并且应该被验证。问题是我们应该验证 StateID 还是实际的 State 关系对象?(在这里使用 FluentValidation,但使用数据注释的情况非常相似)
public class CityValidator : AbstractValidator<City>
{
public CityValidator()
{
// this?
RuleFor(it => it.StateID).NotEmpty();
// or this?
RuleFor(it => it.State).NotNull();
}
}
在第一种情况下,StateID 将被填充,但不会填充状态对象;对于第二种情况,反之亦然。
我可以在我的验证器中放入自定义逻辑来检查其中一个;但是,在我看来,我失去了不显眼的验证属性。这个问题有什么好的、干燥的解决方案吗?
编辑澄清:在示例中,可以通过设置 StateID(对于现有状态)或 State 属性(对于新状态)将 State 分配给 City。那么如何设置验证并仍然在我的视图中的输入上获得“data-val-required”属性?