.NET,EF6 - 禁用递归验证

时间:2016-05-26 20:44:30

标签: c# .net entity-framework validation modelstate

我坚持验证问题。

我使用ModelState来验证来自帖子请求的模型。这是我的模特:

MatchGroup模型

    [Key]
    [Display(Name = "MatchGroupId", ResourceType = typeof(Resources.MatchGroupResources))]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]        
    public Guid MatchGroupId { get; set; }

    [Required(ErrorMessageResourceName = "ValidationRequired", ErrorMessageResourceType = typeof(Resources.GeneralResources))]
    [Display(Name = "MatchGroupName", ResourceType = typeof(Resources.MatchGroupResources))]
    [MinLength(3, ErrorMessageResourceName = "ValidationMinLength", ErrorMessageResourceType = typeof(Resources.GeneralResources))]
    [MaxLength(50, ErrorMessageResourceName = "ValidationMaxLength", ErrorMessageResourceType = typeof(Resources.GeneralResources))]
    public string MatchGroupName { get; set; }

    // foreign key
    public virtual Category Category { get; set; }

CategoryModel

    [Key]
    [Display(Name = "CategoryId", ResourceType = typeof(Resources.CategoryResources))]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid CategoryId { get; set; }

    [Required(ErrorMessageResourceName = "ValidationRequired", ErrorMessageResourceType = typeof(Resources.GeneralResources))]
    [Display(Name = "CategoryName", ResourceType = typeof(Resources.CategoryResources))]
    [MinLength(3, ErrorMessageResourceName = "ValidationMinLength", ErrorMessageResourceType = typeof(Resources.GeneralResources))]
    [MaxLength(50, ErrorMessageResourceName = "ValidationMaxLength", ErrorMessageResourceType = typeof(Resources.GeneralResources))]
    public string CategoryName { get; set; }

正如您所看到的那样," Name"领域。它适用于直接对象,但是当我尝试将MatchGroup对象放入数据库时​​,Controller会抛出ModelState验证错误" Category Name"是必需的。

我的请求(POST)如下所示:         关键:价值

    MatchGroupName: MatchGroup 4
    Category.CategoryId: 5B8D3AC8-8C97-4BCB-AC1A-1D61BDDADEEF

我这样做是因为我最近使用下面的行来附加现有对象:

    context.Category.Attach(model.Category);

当我关闭线条时,它没问题,但是有了它们我无法继续:

    if (!ModelState.IsValid)
    {
        return ResultModelsHelper<MatchGroup>.GetModelStateResponse(ModelState);
    }

我错过了什么吗?如何禁用验证此外来对象的Category对象?也许我从POST获取数据错误,我应该将其传递给其他模型变量?

我在stackoverflow找到的最快的事情是在检查IsValid之前添加一行,但我不知道这是不是一个好主意:

    ModelState.Remove("model.Category.CategoryName");

0 个答案:

没有答案