以编程方式获取 Entity Framework 中 属性 的 'Nullable' 状态

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

我需要为 EF 中的字段获取 Nullable 属性。需要对 Nullable=True 的属性执行一些神奇的代码,我找不到一个有效的解决方案来获取 属性。

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

如有任何帮助,我们将不胜感激。

您可以使用 Nullable.GetUnderlyingType 方法

if (Nullable.GetUnderlyingType(propertyType) != null)
{
    // It's nullable
}

因此您需要数据库中可为空的属性。这意味着 "some magic code" 应该查看 EDMX 的存储模型。 class 模型不包含此信息,更不用说生成的 classes.

以下是获取存储模型中所有可为空属性的列表的方法:

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