验证可保存对象的属性长度最方便的地方在哪里?
我想知道验证持久对象的属性长度最方便的地方在哪里。
比方说,我的数据库中有一个名为 Country 的表,其 CountryCode nvarvhar(3) 。
我有一个映射对象 Country ,其属性 CountryCode 可以保存到 Db 中。
我应该在哪里检查用户设置的国家/地区代码是否不超过 3 个字符:
- 在属性 CountryCode 的设置器中
- 或在保存到 Db 时
可以请您提供建议吗?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我发现最简单的方法是允许将属性设置为任何值(无论如何都是正确的数据类型),然后在保存之前对其进行验证。
我喜欢使用 .Net 内置的验证属性。这保持了与属性关联的逻辑。有一个 StringLengthAttribute 类应该执行以下操作你所要求的技巧。
这些属性位于 System.ComponentModel.DataAnnotations 命名空间中(您需要引用同名的程序集)。
MVC 和 EntityFramework 有一种内置的方法来验证数据。如果您需要自己执行逻辑,这里有一些代码可能会帮助您开始......
I've found that it is easiest to allow properties to be set to any value (of the correct data type anyway) and then validate it before saving it.
I like to use the validation attributes built into .Net. This keeps the logic associated with the property. There is a StringLengthAttribute class that should do the trick for what you are asking for.
The attributes are in the System.ComponentModel.DataAnnotations namespace (you'll need to reference the assembly of the same name).
MVC and EntityFramework have a built in way to validate the data. If you need to perform the logic yourself, here is some code that might help you get started...
根据代码安全建议,所有检查应尽早执行。此外,建议各方自行执行检查,而不依赖其他方的验证。
According to code secure recomendations, all checks should be performed as early as possible. Additionally, it's recommended that each party performs the checks by itself without relying on other parties verifications.