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

守給你的承諾、 提交于 2019-12-02 08:15:10

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

You can use Nullable.GetUnderlyingType Method for this

if (Nullable.GetUnderlyingType(propertyType) != null)
{
    // It's nullable
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!