How to check if a property of an Entity Framework type is Nullable

帅比萌擦擦* 提交于 2019-12-11 06:38:00

问题


I have a EntityDataModel generated from my database. One of the Entity models has two properties that are both string types. One is Nullable=True and the other Nullable=False

How do I check the value of the Nullable property during runtime ?


回答1:


If your properties are decorated with attributes like [Required] or [StringLength] with a property MinimumLength set to a value greater then 0, you could use that property's GetType() method. This method will return an object of type Type and it has a number of other methods like GetCustomAttributes. This method will return all the custom attributes applied to your property.

As I said earlier, if you know which attributes were applied, like the ones mentioned, then using YourObject.YourProperty.GetType().GetCustomAttributes(true) will do the trick. You will need to go through the array and cast the result to the proper attribute.



来源:https://stackoverflow.com/questions/18710697/how-to-check-if-a-property-of-an-entity-framework-type-is-nullable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!