Search code examples
c#entity-frameworknullablepropertyinfo

Get the 'Nullable' state programmatically of a Property in Entity Framework


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.


Solution

  • 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));
    }