实体框架/ ASP MVC关系验证:检查密钥或对象?

时间:2012-11-09 17:18:07

标签: asp.net-mvc entity-framework fluentvalidation

假设我有一个示例实体:

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,但不会填充状态对象;第二种情况反之亦然。

我可以在我的验证器中放置自定义逻辑来检查其中一个;但是,我在视图中丢失了不显眼的验证属性。对这个问题有什么好的DRY解决方案吗?

编辑以澄清:在该示例中,可以通过设置StateID(对于现有状态)或State属性(对于新状态)将状态分配给City 。那么如何设置验证并在我的视图中仍然在输入上获得“data-val-required”属性?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,用户可能会也可能不会选择州?我是对的吗?

为你,

第一种情况:将填充StateID,但不会填充状态对象。

RuleFor(c => c.StateId).NotEmpty().When(s => s.State != null).WithMessage("Please select state.");

第二种情况:反之亦然第二种情况

我从哟明白,这将发生在服务器端,因此你不需要这个规则。

希望这有帮助。