循环在动态上下文数据集以及对象和属性中

时间:2014-01-13 20:25:53

标签: c# entity-framework dynamic reflection objectcontext

我有一个上下文,我想保存上下文中每个数据集中的所有数据,我不想根据每个类类型编写代码。所以我希望有我想要保存它们的类型列表,我想在context.dataset中使用循环然后循环这些属性。

你能帮帮我吗?

     public static void saveAllFiles(Context context)
      {
            var objectTypes = new List<Type>();
        objectTypes.Add(typeof(Language));
        objectTypes.Add(typeof(Employee));

    foreach(Type objectType in objectTypes)
        {
            //var properties = objectType.GetProperties();
            var properties = objectType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            var dataSetObjects = context.Set<objectType>().ToList();

            foreach(var dataSetObject in dataSetObjects)
            {

                 foreach( var  property in properties)
                 {
                     var value = property.GetValue(dataSetObject);
                     var name= property.Name;
                 }

            }
        }
}

1 个答案:

答案 0 :(得分:0)

我不确定您的Context所指的是哪个类,但是这里有一些代码可以让您了解如何获取属性名称和值:

public static void saveAllFiles(Context context)
{
    var objectTypes = new List<Type> {typeof (int), typeof (string)}; 

    foreach(Type objectType in objectTypes)
    {
        var properties = objectType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
        var dataSetObjects = context.Set(objectType);

        foreach(var dataSetObject in dataSetObjects)
        {
            foreach( var property in properties )
            {
                var value = property.GetValue(dataSetObject);
                var name = property.Name;
            }                   
        }
    }
}