Get the 'Nullable' state programmatically

2020-05-04 13:47发布

I need to get the Nullable property out for a field in EF. Some magic code needs to be done on properties that are Nullable=True, and I cannot find a working solution to get the property out.

foreach (PropertyInfo property in (PropertyInfo[])type.GetProperties())
{
   var getPropertyType = property.GetMethod.ReturnTypeCustomAttributes.ToString();

   var getValue = property.GetValue(model);
   bool isNullable = property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>);

   // isNullable always returns false !!!! and I need it to return true if the field is allowed to be null

   if ((getValue == null) && (!isNullable))
   {
   }
}

Class

//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace testApp.Data
{
    using System;
    using System.Collections.Generic;

    public partial class Person
    {
        public int PersonId { get; set; }
        public string Email { get; set; }
    }
}

Any help would be appreciated.

2条回答
Juvenile、少年°
2楼-- · 2020-05-04 14:37

So you want the properties that are nullable in the database. That means that "some magic code" should look into the storage model of the EDMX. The class model doesn't contain this information, let alone the generated classes.

Here's how you can get a listing of all nullable properties in the storage model:

var tableName = "someTable";
var oc = ((IObjectContextAdapter)context).ObjectContext;

var items = oc.MetadataWorkspace.GetItems(DataSpace.SSpace).OfType<EntityType>();
foreach (var entityType in items.Where(e => e.Name == tableName))
{
    var props = string.Join(",", entityType.Properties.Where(p => p.Nullable));
    Debug.WriteLine(string.Format("{0}: {1}", entityType.Name, props));
}
查看更多
一夜七次
3楼-- · 2020-05-04 14:41

You can use Nullable.GetUnderlyingType Method for this

if (Nullable.GetUnderlyingType(propertyType) != null)
{
    // It's nullable
}
查看更多
登录 后发表回答