2

I wonder where is the most convenient place to validate a property length on a persistent object.

Let's say, there is a table called Country in my Db with CountryCode nvarvhar(3).

And I have a mapped object Country wiht property CountryCode which can be saved into Db.

Where should I check if the Country code set by user does not exceed 3 characters:

  • In the setter of property CountryCode
  • OR at the time of saving into Db

Can you please advice?

Thanks

4

2 回答 2

1

根据代码安全建议,应尽早执行所有检查。此外,建议每一方自行执行检查,而不依赖其他方的验证。

于 2011-07-17T07:04:24.967 回答
1

我发现最简单的方法是允许将属性设置为任何值(无论如何都是正确的数据类型),然后在保存之前对其进行验证。

我喜欢使用 .Net 中内置的验证属性。这保持了与属性关联的逻辑。有一个StringLengthAttribute类应该可以满足您的要求。

这些属性位于 System.ComponentModel.DataAnnotations 命名空间中(您需要引用同名的程序集)。

MVC 和 EntityFramework 有一个内置的方法来验证数据。如果您需要自己执行逻辑,这里有一些代码可以帮助您入门...

var ctx = new ValidationContext(obj, null, null);
Validator.ValidateObject(obj, ctx);
于 2011-07-17T07:04:50.623 回答