C#实体框架使用循环选择列 [英] C# entity framework select columns using loop

查看:49
本文介绍了C#实体框架使用循环选择列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中有一个表,其字段的名称如下:

X1,X2,X3,...,X10



我想选择这些列的值并将其分配给变量。我不想写:

I have a table in my database whose fields' name are like:
X1, X2, X3, ... , X10

I want to select the value of these columns and assign it to a variable. I don't want to write:

V[1] = _MyTable.X1; 
V[2] = _MyTable.X2;
.
.
.
V[10] = _MyTable.X10;





我正在寻找类似循环的东西:



I am looking for something like a loop:

for (int i=1; i<=10; i++) 
{
    string _FieldName = "X" + i;
    V[i] = _MyTable._FieldName
}





使用C#和EF。



我尝试了什么:



我在网上看过类似的问题,但是我找不到答案。



Using C# and EF.

What I have tried:

I have read near similar questions on the web, but I couldn't find my answer.

推荐答案

你需要的是使用一种叫做反射的东西。



c - Google搜索 [ ^ ]



反思(C#)| Microsoft Docs [ ^ ]



C#反射的工作原理代码示例 [ ^ ]





要专门达到你想要的效果,你需要做这样的事情



What you need is to use something called reflection.

c - Google Search[^]

Reflection (C#) | Microsoft Docs[^]

How C# Reflection Works With Code Examples[^]


To specifically achieve what you want you'd need to do something like this

var entity = new MyEntity();
            entity.X1 = "ValueX1";
            entity.X2 = "ValueX2";
            entity.X3 = "ValueX3";
            entity.X4 = "ValueX4";
            entity.X5 = "ValueX5";
            entity.X6 = "ValueX6";
            entity.X7 = "ValueX7";
            entity.X8 = "ValueX8";
            entity.X9 = "ValueX9";
            entity.X10 = "ValueX10";


            for (int i = 1; i <= 10; i++)
            {
                var propertyName = string.Format(@"X{0}", i);
                var value =      entity.GetType().GetProperty(propertyName).GetValue(entity, null);
// You get the type from the class/object, then the property name (you have to build it since you have weird property names), then make a call to get value on your object to get the properties value.

                Console.WriteLine("Property {0} - Value {1}", propertyName, value);
            }





以上解决方案返回





The above solution returns

Quote:

Property X1 - Value ValueX1

Property X2 - Value ValueX2

Property X3 - Value ValueX3

物业X4 - 超值X4

物业X5 - 超值X5

物业X6 - 超值X6

物业X7 - 超值X7

物业X8 - 超值X8

物业X9 - 超值X9

物业X10 - 超值X10

Property X1 - Value ValueX1
Property X2 - Value ValueX2
Property X3 - Value ValueX3
Property X4 - Value ValueX4
Property X5 - Value ValueX5
Property X6 - Value ValueX6
Property X7 - Value ValueX7
Property X8 - Value ValueX8
Property X9 - Value ValueX9
Property X10 - Value ValueX10


这篇关于C#实体框架使用循环选择列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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