简体   繁体   English

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

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

I have a EntityDataModel generated from my database. 我有一个从数据库生成的EntityDataModel。 One of the Entity models has two properties that are both string types. 实体模型之一具有两个均为字符串类型的属性。 One is Nullable=True and the other Nullable=False 一个是Nullable = True,另一个是Nullable = False

How do I check the value of the Nullable property during runtime ? 如何在运行时检查Nullable属性的值?

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. 如果您的属性装饰有[Required][StringLength]的属性,并且属性MinimumLength的值设置为大于0,则可以使用该属性的GetType()方法。 This method will return an object of type Type and it has a number of other methods like GetCustomAttributes . 此方法将返回Type的对象,并且它具有许多其他方法,例如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. 就像我之前说的,如果您知道应用了哪些属性(如提到的属性),则使用YourObject.YourProperty.GetType().GetCustomAttributes(true)可以解决问题。 You will need to go through the array and cast the result to the proper attribute. 您将需要遍历数组并将结果转换为适当的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何禁用实体框架来创建Nullable属性 - How to disable entity framework from creating Nullable property's 如何将实体框架4.5设置为永不将任何属性设置为Nullable - How to set entity framework 4.5 to never set any property as Nullable 实体类型的属性不能用于具有实体框架的 Nullable1 类型的对象 - The property on entity type cannot be used for objects of type Nullable1 with Entity Framework 实体框架不可为空的列映射到可为空的实体属性 - Entity Framework Non-nullable column is mapped to a nullable entity property 实体框架中不可为空的导航属性为null - Non nullable navigation property is null in Entity Framework 在实体框架中以编程方式获取属性的“空”状态 - Get the 'Nullable' state programmatically of a Property in Entity Framework 实体框架使双精度为可空属性 - Entity Framework making double a nullable property 检查属性是类型还是可空类型 - Check if property is either of type or it's nullable type 实体框架:将nullable设置为false,但是type仍然可以为null - Entity Framework: Set nullable to false, but type is still nullable 实体框架-检查属性是否已映射 - Entity Framework - Check if property is mapped
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM