简体   繁体   中英

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

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM