我怎样才能获得EntityObject类型的类型并用数据填充它?

时间:2012-07-30 15:47:23

标签: c# entity-framework

我想要创建一个方法来循环实体对象上的属性列表,检查每个属性并在其中粘贴一些虚拟数据。这可能吗?我的尝试在下面,但我被卡住了......(评论详细说明了我无法解决的问题)......

private static void SetAllNonNullableProperties(EntityObject airport, string uniqueMessage)
{
    Type t = airport.GetType();
    PropertyInfo[] props = t.GetProperties();

    foreach (var prop in props)
    {
        //1) How do I see if this property is nullable?
        //2) How do I tell the type so that I can stick a string/bool/datetime in it with dummy data?
    }
}

2 个答案:

答案 0 :(得分:0)

您好 Exitos , 试试这个:

public bool isNullableProperty(PropertyInfo p)
{
    bool result = false;
    foreach (object attr in p.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), false))
        if (!(((EdmScalarPropertyAttribute)attr).IsNullable))
            result = true;
    return result;
}

public void SetAllNonNullableProperties(System.Data.Objects.DataClasses.EntityObject airport)
{
    Type t = airport.GetType();
    PropertyInfo[] props = t.GetProperties();

    foreach (PropertyInfo p in props)
    {
        if (isNullableProperty(p)) 
            // Now i know the secrets... ;)

        if (p.PropertyType() == typeof(DateTime))
            //  This property type is datetime
        else if (p.PropertyType() == typeof(int))
            // And this type is integer

    }

}

答案 1 :(得分:0)

尝试类似的东西:

using System;
using System.Reflection;

namespace ReflectionProp
{
    class Program
    {
        static void Main(string[] args)
        {
            Foo obj = new Foo { Name = "obj", Num = null, Price = null };
            Console.WriteLine(obj);

            SetAllNonNullableProperties(obj, 100, 20);

            Console.WriteLine(obj);

            Console.ReadKey();
        }

        private static void SetAllNonNullableProperties(Foo obj, int num, decimal dec)
        {
            Type t = obj.GetType();
            PropertyInfo[] props = t.GetProperties();

            foreach (var prop in props)
            {
                // check if property is nullable
                if (Nullable.GetUnderlyingType(prop.PropertyType) != null)
                {
                    // check if property is null     
                    if (prop.GetValue(obj, null) == null)
                    {
                        if(prop.PropertyType == typeof(Nullable<int>))
                            prop.SetValue(obj, num, null);

                        if (prop.PropertyType == typeof(Nullable<decimal>))
                            prop.SetValue(obj, dec, null);
                    }                    
                }
            }
        }
    }

    public class Foo
    {
        public Nullable<int> Num {get;set;}
        public string Name { get; set; }
        public Nullable<decimal> Price { get; set; }

        public override string ToString()
        {
            return String.Format("Name: {0}, num: {1}, price: {2}", Name, Num, Price);
        }
    }
}