如何检查实体框架类型的属性是否可为空

如何检查实体框架类型的属性是否可为空

问题描述:

我有一个从数据库生成的EntityDataModel。
实体模型之一具有两个均为字符串类型的属性。
一个是Nullable = True,另一个是Nullable = False

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

如何在运行时检查Nullable属性的值?

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

如果您的属性以 [必需] [属性为 MinimumLength 的StringLength] 设置为大于0的值,则可以使用该属性的GetType()方法。此方法将返回类型为 Type 的对象,并且它具有许多其他方法,例如 GetCustomAttributes 。此方法将返回应用于属性的所有自定义属性。

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.

正如我之前说的,如果您知道应用了哪些属性(如所述属性),则使用 YourObject.YourProperty.GetType()。GetCustomAttributes (true)可以解决问题。您将需要遍历数组并将结果强制转换为适当的属性。

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.