gpt4 book ai didi

entity-framework - Entity Framework 复杂类型自定义验证,停止验证递归

转载 作者:行者123 更新时间:2023-12-04 08:29:21 24 4
gpt4 key购买 nike

我们使用复杂的类型来管理可翻译字段,如下所示:

[ComplexType]
public class Translated
{
[Required]
public string NL { get; set; }

[Required]
public string EN { get; set; }

[ScaffoldColumn(false)]
public string TranslatedText
{
get
{
return Util.Translate(NL, EN);
}
}
}

我们要求字段存在。但是在某些情况下,整个Translated字段是可选的,如下所示:
public class Question
{
...

[Optional(ErrorMessage="Foo")]
public Translated Description { get; set; }

...
}

但是,似乎已计算了Optional属性,当它返回false时,结果将不做任何事情。
class OptionalAttribute : ValidationAttribute 
{
public override bool IsValid(object value)
{
return false;
}
}

当我将可选属性放在非复杂类型上时,它可以按预期工作,错误消息将始终为Foo。

最终目标是在两种情况下都允许Description为空,但是当其中一个字段被填充时,错误当然应该传播。

停止验证递归将使该字段为可选字段,但如果已将 填充为,则也将阻止对字段进行验证。

关于如何做到这一点的任何想法?

最佳答案

在字符串属性上使用数据注释[Required]将在数据库中创建不可为空的字段。从您的描述看来,有时您会希望这两个值都为null。

我建议您实现自己的验证,以定义使这些字段为可选的内容。

[ComplexType]
public class Translated : IValidatableObject
{
public string NL { get; set; }

public string EN { get; set; }

[NotMapped]
public string TranslatedText
{
get
{
return Util.Translate(NL, EN);
}
}

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (!string.IsNullOrEmpty(NL) && string.IsNullOrEmpty(EN))
yield return new ValidationResult("EN is required if NL is entered.");

if (!string.IsNullOrEmpty(EN) && string.IsNullOrEmpty(NL))
yield return new ValidationResult("NL is required if EN is entered.");
}
}

关于entity-framework - Entity Framework 复杂类型自定义验证,停止验证递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5635278/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com