【发布时间】:2021-01-16 15:10:14
【问题描述】:
我正在将客户端的数据迁移到需要验证所有属性的新数据库 (SQL SERVER)。 我尝试添加数据注释,但没有按预期工作。
这是我的示例代码:
public class SellerDetailModel
{
[Required, RegularExpression("[0-9]{2}[0-9A-Z]{13}")]
public string GSTNumber;
[Required, StringLength(100, MinimumLength = 3)]
public string LegalName;
[StringLength(100, MinimumLength = 3)]
public string TradingName;
[Required, StringLength(100, MinimumLength = 3)]
public string Address1;
[StringLength(100, MinimumLength = 3)]
public string Address2;
[Required, StringLength(50, MinimumLength = 3)]
public string Location;
[Required, StringLength(6)]
public int PinCode;
[Required, StringLength(2, MinimumLength = 1)]
public string StateCode;
[StringLength(12, MinimumLength = 6)]
public string ContactNumber;
[Required, StringLength(100, MinimumLength = 6)]
public string EmailId;
}
现在,在另一个类(业务逻辑)中,我正在为这个类分配值。
//"invoice" is an object having seller related data
SellerDetailModel dataTransferObject = new SellerDetailModel
{
GSTNumber = invoice.SellerGSTNumber,
LegalName = invoice.SellerLegalName,
TradingName = invoice.SellerTradingName,
Address1 = invoice.SellerAddress1,
Address2 = invoice.SellerAddress2,
Location = invoice.SellerLocation,
PinCode = Convert.ToInt32(invoice.SellerPinCode),
StateCode = invoice.SellerStateCode,
ContactNumber = invoice.SellerContactNumber,
EmailId = invoice.SellerEmailId,
};
但即使在添加了所需的属性、Regex、String Length 等之后......它根本没有被验证, 它仍然接受所有的空值。 有人可以帮我如何验证这些属性吗?
如果迁移过程中出现错误,我只想创建一个日志数据。
编辑
我已经尝试过下面的方法,但还是不行……
public string Validate()
{
ValidationContext context = new ValidationContext(this);
List<ValidationResult> results = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(this, context, results, true);
if (!isValid)
{
StringBuilder sbrErrors = new StringBuilder();
foreach (var validationResult in results)
{
sbrErrors.AppendLine(validationResult.ErrorMessage);
}
return sbrErrors.ToString();
}
else
return string.Empty;
}
var validation = dataTransferObject.Validate() //always gives string.Empty
【问题讨论】:
-
属性不验证任何东西。他们告诉验证者如何验证。你有一个验证器吗?而且,验证模型属性的任务与您使用的数据库几乎无关。
-
@GSerg 你能解释一下如何添加验证器吗? (我是 C# 新手)
-
我试过了,但还是不行,
标签: c# regex validation data-annotations data-modeling