在实体框架中以编程方式获取属性的“空"状态 [英] Get the 'Nullable' state programmatically of a Property in Entity Framework

查看:103
本文介绍了在实体框架中以编程方式获取属性的“空"状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取EF中的字段的Nullable属性.需要对Nullable = True的属性执行一些魔术代码,但我找不到有效的解决方案来删除该属性.

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

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

任何帮助将不胜感激.

推荐答案

因此,您需要数据库中可为空的属性.这意味着一些魔术代码"应该考虑到EDMX的存储模型.类模型不包含此信息,更不用说生成的类了.

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

这篇关于在实体框架中以编程方式获取属性的“空"状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆