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

后端 未结 2 701
春和景丽
春和景丽 2021-01-26 08:32

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

相关标签:
2条回答
  • 2021-01-26 08:46

    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));
    }
    
    0 讨论(0)
  • 2021-01-26 08:54

    You can use Nullable.GetUnderlyingType Method for this

    if (Nullable.GetUnderlyingType(propertyType) != null)
    {
        // It's nullable
    }
    
    0 讨论(0)
提交回复
热议问题